2

I'm trying to display an image using an xml file and SimpleXML

The XML code is

<icons>
  <icon size="tiny"    href="/FF02-tiny.jpg"    />
  <icon size="sidebar" href="/FF02-sidebar.jpg" />
  <icon size="full"    href="/FF02-full.jpg"    />
</icons>

I want to get the href attribute for the size="full" line.

I've tried

icons->icon->attributes()->href

but this just gives me the first 'tiny' size. I know I should be using xpath but I am lost.

hakre
  • 193,403
  • 52
  • 435
  • 836
kaillum
  • 23
  • 3

2 Answers2

2

Yes, you can select the attribute node with an xpath expression:

list($iconHref) = $xml->xpath("//icon[@size='full']/@href");
echo $iconHref;
hakre
  • 193,403
  • 52
  • 435
  • 836
michi
  • 6,565
  • 4
  • 33
  • 56
  • thanks for your suggestion... I tried this but it still gave me an array as the output. The answer by Boundless worked a treat... – kaillum Feb 20 '13 at 13:35
  • 1
    @kaillum: I edited my answer so it would work. The way I suggest will work even if the structure of the XML changes. – michi Feb 20 '13 at 15:06
0

$icons->icon will give you a SimpleXMLElement object that gives access to all icon child-elements of the $icons object.

From there you need to select which icon you want to get the attribute for. That works with array-like access and a numeric value for the zero-index child element and a string value for the attribute:

// specify what icon you want (third)
// and the attribute (href)
$icons->icon[2]['href'];

You find that documented in the PHP manual with the SimpleXML basic examples (Example #3 and Example #5).

However this does not work if the position of the element you look for changes. So it's suggested that you use a more specific xpath-expression instead.

Community
  • 1
  • 1
Boundless
  • 2,444
  • 2
  • 25
  • 40
  • You're welcome. Also, if your XML varies ie 'full' isn't always the 3rd icon you'll need to try something different. – Boundless Feb 20 '13 at 13:58