-2

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!

Peon
  • 7,902
  • 7
  • 59
  • 100
user1294097
  • 153
  • 1
  • 5
  • 14

2 Answers2

1

You should do something like this instead:

foreach ($xml->children() as $child)
{
    echo '<img src="' . $child['path'] . '" alt="gallery image" />';
}
Robin V.
  • 91
  • 5
  • Thanks This works great, i couldn't find it mostly cause i didn't know what it was called, I'm new to xml and php. – user1294097 Jul 28 '12 at 18:32
0

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.

nickb
  • 59,313
  • 13
  • 108
  • 143
  • Or you can just go straigth for the variable like `$xml -> children() -> attributes` :) – Peon Jul 27 '12 at 18:02
  • `children()` will be an array of SimpleXML elements - I don't think that will work. – nickb Jul 27 '12 at 18:04
  • Sorry, wasn't testing, just fast writing the idea. That's why I didn't post it as an answer m8 :) – Peon Jul 27 '12 at 18:05