1

i have a xml structure of the following form to be parsed using 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. 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

2 Answers 2

3

This works for me:

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

See SimpleXML Basic usage.

Sign up to request clarification or add additional context in comments.

Comments

2

The url is an attribute, not a child element. Try this:

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

Documentation here

2 Comments

Thanks for the reply nick. But i seem to be having a strange problem here. print $images->image[0]->attributes()->url prints the url of the first image correctly,but again the below loop for printing the urls of all the images does not work...what could be wrong here ? foreach($images as $image) { print $image->attributes()->url; }
You also need to do foreach ($images->image as $image)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.