Tips and tricks for LAMP (Linux Apache MySQL PHP) developers.

When I cant find a suitable solution to a problem and have to work it out for myself I'll post the result here so hopefully others will find it useful. (All code is offered in good faith. It may not be the best solution, just a solution).

Thursday 20 November 2014

SimpleXML and mixed, nested namespaces

I work with several third party marketplace APIs, one of which is Amazon's MWS API.
When processing their GetMatchingProductForId response I discovered that they sometimes namespace the XML nodes (with ns2).

PHP's SimpleXML doesn't allow access to namespaced nodes via the usual interface of $simpleXml->node but I found you can specify a namespace to the children() method like so:

$simpleXml
    ->children('ns2', true)
    ->namespacedNode

That works great but then I hit a problem. As I mentioned, Amazon namespace some of the nodes but not all and the node I was really after was not namespaced itself but was a child of a namespaced node. After I applied the code above I found that I couldn't access the child node:

$simpleXml
    ->children('ns2', true)
    ->namespacedNode
    ->nonNamespacedNode

I thought all was lost until I discovered you can reset SimpleXML's namespace filter back to none again with another call to children() so you can get at the non-namespaced child node:

$simpleXml
    ->children('ns2', true)
    ->namespacedNode
    ->children()
    ->nonNamespacedNode