2014-01-28 225 views
0

顯示XML值我有一個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

這是什麼?語法錯誤第11行。'$ img1 = $ cars-> image');'應該是'$ img1 = $ cars-> image;' – michi

+0

Ups,在應對方面我有點小錯誤,但實際上它不解決我需要的問題 – user2421781

回答

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

+0

你能告訴,什麼意思。 PHP_EOL? – user2421781

+0

End Of Line - > line-break,請參閱http://stackoverflow.com/questions/128560/when-do-i-use-the-php-constant-php-eol – michi

+0

非常感謝您快速回答! – user2421781