A small SimpleXML gotcha (with namespaces)

DZone 's Guide to

A small SimpleXML gotcha (with namespaces)

· Web Dev Zone ·
Free Resource

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 xlink:href="something_or_other">a text</a>

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 :)

Originally posted at Left on the Web


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}