0

我有以下 xml 文档:

<?xml version="1.0"?>  
<root> 
<offers count="3009">
<offer>
    <offerId>25</offerId>
    <offer_type>for sale</offer_type>
    <offer_status>available</offer_status>
     <building_floors></building_floors>
    <title>title</title> 
<photos count="4">
<photo zIndex="1">1.jpg</photo>
<photo zIndex="2">2.jpg</photo>
<photo zIndex="3">3.jpg</photo>
<photo zIndex="4">4.jpg</photo>
     </photos>
  </offer>
</offers>
</root>

我正在使用这个 php 代码从 xml 中获取结果:

$xml = simplexml_load_file("offers.xml") 
       or die("Error: Cannot create object");
foreach($xml->children() as $offers){
    foreach($offers->children() as $offer => $data){
    echo $data->offerId;echo "<br />";//and so on for each element
          foreach ($xml->offers->offer->photos->photo as $aaa){
         $photos=$aaa; echo "<br />";
         //echo $xml;
         $photo = explode("<br /> ", $photos);
            foreach($photo as $value) echo $value; echo '<br />';//echo $value
        }
    }
}

当我尝试循环照片元素时,我会得到所有照片,但仅限于第一个报价。我的问题是我做错了什么以及为什么我没有为每个报价获取照片?

4

1 回答 1

0

问题在于您检索照片元素的方式。您从根元素开始,因此它始终为您提供相同的节点。你应该像这样使用 $data :

foreach ($data->photos->photo as $aaa){

清理一下您的代码,您应该使用它来显示照片元素:

$xml = simplexml_load_file("offers.xml") or die("Error: Cannot create object");
foreach($xml->children() as $offers){
    foreach($offers->children() as $offer){
        echo "Offer id : " . $offer->offerId . "<br>";
        foreach ($offer->photos->photo as $photo){
            $val = (string) $photo;
            echo $val . "<br>";
        }
    }
}
于 2012-11-13T08:48:54.827 回答