Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A small SimpleXML gotcha (with namespaces)

DZone's Guide to

A small SimpleXML gotcha (with namespaces)

· Web Dev Zone
Free Resource

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

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

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

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 }}