我有以下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
}
}
}
当我尝试循环播放照片元素时,我会收到所有照片,但仅限于第一个优惠。 我的问题是我做错了什么以及为什么我没有为每个报价拍照?
答案 0 :(得分: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>";
}
}
}