Over a million developers have joined DZone.

A small SimpleXML gotcha (with namespaces)

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}