Left on the Web

A small SimpleXML gotcha (with namespaces)

I've so far worked only very little with XML with namespaces, especially in terms of parsing it. Therefor, I was quite stumped today on the parsing of a particular snippet of XML which contained an element that had an xlink:href attribute. I just couldn't get that attribute's value out. The solution, as often seems to be the case, is quite simple.

It was my colleague Dynom who saved the day for me. He pointed me towards the second optional parameter of the attributes() method of the SimpleXMLElement object. Given the following snippet (within a larger snippet):

a text

I was using the first parameter of attributes (the namespace) to let SimpleXML know from which namespace I wanted to get the attributes:

$attributes = $xml->a->attributes('xlink' );
echo $attributes['href'];

This didn't work. $attributes['href'] didn't exist, and var_dump-ing the $attributes array returned an empty array. However, clearly I should learn to read better, because the manual does mention the second parameter $is_prefix, which is a boolean that indicates if the attributes are actually prefixed by the namespace. As, in the above case, this is true, I have to set it to true (it defaults to false). So with this it worked:

$attributes = $xml->a->attributes('xlink', true);
echo $attributes['href'];

These are the kinds of details that you can get stumped on for ages, so I hope that people reading this will keep it in mind and remember it when they encounter a similar situation :)


Add comment

Comments

gravatar : what all those smilies?
gravatar left: good point, I removed the smiley from the code example. I hadn't noticed it for some reason.

I also noticed from your comment another bug ... the name isn't a requirement it seems :)
gravatar arne: Hey, thanks for the tip :)

It's saves me a lot of trying!
© 2004 - 2008 Stefan Koopmanschap + Powered by Symfony, photos powered by Flickr, links powered by Ma.gnolia, Shanghai smilies by Iconbuffet. Feeds: rss / atom. Left on the Web v4.2.3