SimpleXML and parsing namespaced attribute

SimpleXML is really good, this is especially more from the heart as its coming from someone who spent a decent amount of time using DOM API to parse xml in Java, though XPath was mostly a saviour. I usually get stuck when I there is an edge case or parsing some data format that I haven’t had to use. Recently I had to parse an XML feed which contained some attributes link this:

<a foo:param="bla">Some sample text</a>

Trying to access is using the following code didnt work for me:

$attributes = $xml->a->attributes('foo');
echo $attributes['param'];

However as mentioned in the manual I needed to explicitly specify that the attribute is prefixed using the second argument. The default value for the second argument is false.

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

I spent a while trying to figure this out, hope this saves you some time. Btw simpleXML is awesome.

About rp

Architect for large, highly scalable LAMP applications and Technical Manager with special focus on metrics based continuous improvement of teams and products. Rajat has close to a decade of experience of a very wide range of skills related to infrastructure, middleware, app servers all the way to front-end technologies and software development methodologies including agile, iterative waterfall, waterfall as well as ah-hoc startup using the right approach in the right context to reduce time to market.