News Archive
PhpRiot Newsletter
Your Email Address:

More information

Fetching Namespaced XML Elements With SimpleXML

Note: This article was originally published at Planet PHP on 3 November 2010.
Planet PHP
Recently I was working with some google APIs and needed to retrieve some namespaced elements from the result set. This confused me more than I expected it to so here's my code for the next time I need it (and if you use it too, then great!)

I was reading from their analytics data feed API, this returns a few key fields and then multiple tags, each with namespaced children. The entry tags look something like:
gd:etag="W/"Ak8EQX47eSp7I2A9Wx5VFks."" gd:kind="analytics#datarow"
A 2010-10-09T17:00:00.001-07:00
A ga:date=20101005
A rel="alternate" type="text/html" href=""/
A name="ga:date" value="20101005"/
A confidenceInterval="0.0" name="ga:visits" type="integer" value="329"/


While you can access the non-namespaced elements either by addressing them directly or by iterating over the parent, the namespaced ones remain determinedly invisible, until you call asXML() on the node again. However we can retrieve them easily if we specify their namespace.

Retrieving Namespaces

When I get the response from my request to the API, I simply load the resulting string as a SimpleXMLElement. To get the namespaces, I simply call:

$namespaces = $xml-getNamespaces(true);
And I get an array with prefixes and full URLS, looking something like this:

[] =
[gd] =
[openSearch] =

Truncated by Planet PHP, read more at the original (another 1687 bytes)