2009-12-22 101 views
1

我使用PHP simplexml解析了以下形式的xml結構。在PHP中使用SimpleXML解析XML

<books> 

<book> 
<title>XYZ</title> 
<author> someone </author> 
<images> 
<image type="poster" url="<url>" size="cover" id="12345"/> 
<image type="poster" url="<url>" size="thumb" id="12345"/> 
</images> 
</book> 

<book> 
<title>PQR</title> 
<author> someoneelse </author> 
<images> 
<image type="poster" url="<url>" size="cover" id="67890"/> 
<image type="poster" url="<url>" size="thumb" id="67890"/> 
</images> 
</book> 

</books> 

假設我想打印第一本書的標題。我能夠做到這一點使用

​​

但是,當我嘗試打印這本書的所有圖像網址它不起作用。代碼即時通訊使用是:

$books = $xml->books; 
$book = $books->book[0]; //Get the first book 
$images=$book->images; 

foreach($images as $image) //This does not work 
{ 
    print $image->url; 
} 

任何方式來解決這個問題?

謝謝

回答

1

url是一個屬性,而不是子元素。試試這個:

print $image->attributes()->url; 

Documentation here

+0

感謝您的回覆暱稱。但我似乎在這裏有一個奇怪的問題。打印$ images-> image [0] - > attributes() - > url正確打印第一張圖片的url,但下面的循環打印所有圖片的url不起作用......這裏可能是錯誤的? foreach($ image as $ image){print $ image-> attributes() - > url; } – John 2009-12-22 02:56:59

+1

你還需要做foreach($ images-> image as $ image) – jmans 2009-12-22 03:14:17

2

這個工作對我來說:

foreach ($xml->book[0]->images->image as $image) { 
    echo $image['url'] . "\n"; 
} 

SimpleXML Basic usage