2017-02-22 135 views
0

我試圖在我的網站上創建一個工作表,從XML提要中獲取信息我有權訪問...我已經看過各種示例在線和視頻,但我無法看到了解它是如何工作的。我的XML飼料返回以下節點結構:使用simplexml循環通過xml節點

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

我已經成功通過一個項目拉動與此代碼:

<?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; 
?> 

但將其轉換成的foreach似乎是在那裏我掙扎。下面我試過的代碼沒有運氣;

<?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; 
?> 

感謝所有:)

回答

0

OK看起來很簡單的運行就像我找到了解決辦法。繼承人爲我工作的代碼,再加上它包含的代碼一點點,拉出來重複(它顯示每個項目的4倍!)...

<?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); 
      ?> 
0

documentation

注摘自:

屬性($影片 - >電影在前面的例子)不是數組。他們 是可迭代和可訪問的對象。

隨着該記住的,你可以在節點與foreach

$xml = simplexml_load_file($url); 
foreach ($xml->OutputVacancyAsXml->Vacancy as $vacanacy) 
{ 
    echo (string)$vacanacy->Job; // Echo out the Job Title 
} 
+0

謝謝KhorneHoly - 所以我把它放在一起,並拿出與此,但它似乎並沒有工作... <?php $ html =「」; $ url =「https://www.octopus-hr.co.uk/recruit/OutputVacancyAsXml.aspx?CompanyID=400-73A3BCA1-D952-4BA6-AADB-D8BF3B495DF6」; $ xml = simplexml_load_file($ url); foreach($ xml-> OutputVacancyAsXml->空缺爲$ vacanacy) { echo(string)$ vacanacy-> Job; //回聲輸出職位 } ?> –

+0

不知道我應該補充說KhorneHoly - 沒有代碼區域的外觀... –