简体   繁体   English

在PHP中使用SimpleXML解析XML

[英]Parsing XML using SimpleXML in PHP

i have a xml structure of the following form to be parsed using PHP simplexml. 我有以下形式的xml结构,可以使用PHP simplexml进行解析。

<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>

Suppose i want to print the title of the first book. 假设我要打印第一本书的标题。 I am able to do that using 我能够使用

$books = $xml->books; 
$book = $books->book[0]; //Get the first book
print $book->title; //This works

But,when i try to print all the image urls for this book it does not work. 但是,当我尝试打印本书的所有图像URL时,它将无法正常工作。 The code im using is: 我使用的代码是:

$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;
}

Any way to fix this problem ? 有什么办法解决这个问题?

Thank You 谢谢

This works for me: 这对我有用:

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

See SimpleXML Basic usage . 请参阅SimpleXML Basic用法

The url is an attribute, not a child element. url是属性,而不是子元素。 Try this: 尝试这个:

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

Documentation here 这里的文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM