This question already has an answer here:
I have an xml that looks something like this:
<gallery server="5">
<image path="http://i.imgur.com/8n5MB.jpg"/>
<image path="http://i.imgur.com/TIXL2.jpg"/>
</gallery>
I'm trying to get the images to display in one page using PHP. This is what I have:
$xml = simplexml_load_file('./images.xml');
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . "<br />";
}
My problem is that this only outputs the following
gallery
image
image
image
I can't find any information on how to read the information of the tag itself, any pointers? Thanks!
</div>
You should do something like this instead:
foreach ($xml->children() as $child)
{
echo '<img src="' . $child['path'] . '" alt="gallery image" />';
}
You can use XPath to select the elements, then grab the path
attribute from the element's list of attributes, like this:
foreach( $xml->xpath('//image') as $image)
{
$attributes = $image->attributes();
echo $attributes['path'] . "<br />";
}
So this loop will only loop over the <image>
tags. For every <image>
tag, it grabs that tag's attributes and prints out the path
attribute.