显示具有特定属性的xml值

时间:2014-01-28 22:19:46

标签: php xml xml-parsing simplexml

我有那个php解析器,它的工作非常完美,但我只得到了第一张图片:

<?php
header("Content-Type: text/html;charset=UTF-8");
$xml = simplexml_load_file("xmlf.xml") 
or die("Error: Cannot create object");
foreach($xml->children() as $cars){

$code = "$cars->code";
$category = "$cars->category_id";
$brand = "$cars->brand";
$name = "$cars->product_name";
$img1 = $cars->image;

echo $code;
echo "^";
echo $name;
echo "^";
echo $descc;
echo "^";
echo $category;
echo "^";
echo $weight;
echo "^";
echo $brand;
echo "^";
echo $img1;
echo "\n";

} ?>

这里是我需要解析的xml文件示例:

    <?xml version="1.0" encoding="UTF-8"?>
<xml> 
 <good> 
<code>CODE1</code>
<product_name>NAME</product_name>
<brand></brand>
<category_id>725</category_id> 
<category>CAT</category>
<price>1.42</price>
<quantity>2</quantity>
<image count="1">http://imagelink.jpg</image> 
<image count="2">http://imagelink.jpg</image> 
<image count="3">http://imagelink.jpg</image> 
<image count="4">http://imagelink.jpg</image> 
<image count="5">http://imagelink.jpg</image> 
</good>

 <good> 
<code>CODE2</code>
<product_name>NAME</product_name>
<brand></brand>
<category_id>725</category_id> 
<category>CAT</category>
<price>1.42</price>
<quantity>2</quantity>
<image count="1">http://imagelink.jpg</image> 
<image count="2">http://imagelink.jpg</image> 
</good>

</xml>

请帮助我,我需要更改以解析此xml中的所有图像?我花了大约六个小时找到了解决方案,但还没有运气。

1 个答案:

答案 0 :(得分:2)

如果有多个<image>

foreach ($xml->good as $car) {

    echo $car->code . PHP_EOL;
    echo $car->category . "($car->category_id)" . PHP_EOL;
    echo $car->brand . PHP_EOL;

    foreach ($car->image as $image)
        echo "image No." . $image['count'] . ": " . $image . PHP_EOL;

}

看到它有效:https://eval.in/95876