About the Author

author photo

Adam Trachtenberg is the Director of the LinkedIn Developer Network, where he oversees developer relations and marketing for the LinkedIn Platform. Before LinkedIn, Adam worked at eBay in platform product management and marketing. Even earlier, he co-founded Student.Com and TVGrid.com. Adam is the author of PHP Cookbook and Upgrading to PHP 5. He lives in San Francisco.

See All Posts by This Author

PHP Trivia Contest: DOM + Default Namespaces

Here’s a question based on a recent PHP bug report which shows why DOM is fun.

Given the following line of PHP:

$xml = DOMDocument::loadXML(
'<r xmlns="urn:a"/>');

The easy way to print the namespace URI of the root node, urn:a, is:

echo $xml->documentElement->namespaceURI;

But how do you retrieve it using DOMElement::GetAttributeNS()? What are the two magical input parameters to coax that value out?

There Are 4 Responses So Far. »

  1. I suppose it’s cheating to suggest:

    $xpath = new DOMXPath($xml);
    echo $xpath->query(‘/*[local-name(.)=”r”]’)->item(0)->namespaceURI;

    Section 3 of http://www.w3.org/TR/xml-names/ says:

    The prefix xmlns is used only to declare namespace bindings and is by definition bound to the namespace name http://www.w3.org/2000/xmlns/.

    Which implies that:

    $xml->documentElement->getAttributeNS(‘http://www.w3.org/2000/xmlns/’,’xmlns’) should work, but it doesn’t.

  2. Yea, XPath is cheating. That’s why I called out getAttributeNS().

    But you’re close enough, as:


    Does work. However, I’m not sure if it’s supposed to. :)

  3. Ooh, that’s kooky. I can see why getAttributeNS(’http://www.w3.org/2000/xmlns/’,”) works over ‘xmlns’ as the second argument — if ‘xmlns’ is the “namespace prefix”, as it is obviously with something like xmlns:pants=”http://whatever/”. you’d want to call getAttributeNS(’http://www.w3.org/2000/xmlns/’,’pants’), but the special case of prefix-but-no-localname is weird.

  4. xmlns is not the prefix name. It is the default namespace identifier. Which in case of the default namespace has an empty prefix. So getAttributeNS(’http://www.w3.org/2000/xmlns/’,”) would work, as it should. If the namespace was xmlns:prefix then correctly, ‘prefix’ would be the argument to getAttributeNS.

    The php5 DOM implementation is a leap over php4 and I’m looking forward to namespace implementation in php5.3+ & php6.

    Not perfect though, Just logged a bug for createAttributeNS.