Search code examples
phpxmlforeachsimplexml

Loop through xml nodes with simplexml


Im trying to create a table of Jobs on my site, pulling info from an xml feed I have access to... I've looked at various examples online and videos but I can't seem to understand how it works. My xml feed returns the following node structure:

<OutputVacancyAsXml>
  <Vacancy>
    <VacancyID></VacancyID>
    <Job></Job>
    <ClosingDate></ClosingDate>
  </Vacancy>
</OutputVacancyAsXml>

I've had success with pulling through one item with this code:

<?php
    $x = simplexml_load_file('https://www.octopus-hr.co.uk/recruit/OutputVacancyAsXml.aspx?CompanyID=400-73A3BCA1-D952-4BA6-AADB-D8BF3B495DF6');
    echo $x->Vacancy[5]->Job;
?>

But converting it to foreach seems to be where I'm struggling. Heres the code I have tried so far with no luck;

<?php
$html = "";
$url = "https://www.octopus-hr.co.uk/recruit/OutputVacancyAsXml.aspx?CompanyID=400-73A3BCA1-D952-4BA6-AADB-D8BF3B495DF6";
$xml = simplexml_load_file($url);
for ($i = 0; $i < 10; $i++) {
  $title = $xml->OutputVacancyAsXml->Vacancy[$i]->job;
  $html .= "<p>$title</p>";

}
echo $html;
?>

Thanks all :)


Solution

  • Ok looks like I found a solution. Heres the code that worked for me plus it contains a little bit of code that pulls out duplicated (it was displaying each item 4 times!)...

    <?php
    
    
                  $x = simplexml_load_file('https://www.octopus-hr.co.uk/recruit/OutputVacancyAsXml.aspx?CompanyID=400-73A3BCA1-D952-4BA6-AADB-D8BF3B495DF6');
    
                $num = count($x->Vacancy);
    
                //echo "num is $num";
    
                $stopduplicates = array();
    
                for ($i = 0; $i < $num; $i++) {
    
    
               $job = $x->Vacancy[$i]->Job;
                  $closingdate = $x->Vacancy[$i]->ClosingDate;
                  // http://stackoverflow.com/questions/416548/forcing-a-simplexml-object-to-a-string-regardless-of-context
                  $vacancyid = (string) $x->Vacancy[$i]->VacancyID; 
    
    
                    if (!in_array($vacancyid, $stopduplicates)) {  
    
    
    
    
                  echo '
                    <tr class="job-row">
                      <td class="job-cell">'.$job.'</td>
                      <td class="date-cell">'.$closingdate.'</td>
                      <td class="apply-cell">
                        <a href="https://www.octopus-hr.co.uk/recruit/application/apply.aspx?cid=400-73A3BCA1-D952-4BA6-AADB-D8BF3B495DF6&VacancyID='.$vacancyid.'" target="_blank" class="btn btn-teal btn-md btn-job" role="button">Apply Here</a>
                      </td>
                    </tr>';       
                    }
                 $stopduplicates[] = $vacancyid; 
                } //print_r($stopduplicates);
              ?>