About the Author

author photo

Adam Trachtenberg is the Director of Platform and Services at eBay. Before eBay, Adam co-founded and served as vice president for development at two companies, Student.Com and TVGrid.Com. Adam is the author of Upgrading to PHP 5 and coauthor of PHP Cookbook. He lives in San Francisco, California.

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?

Popularity: 40% [?]

There Are 4 Responses So Far. »

  1. I suppose it’s cheating to suggest:

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

    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:

    getAttributeNS(’http://www.w3.org/2000/xmlns/’,”)

    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.
    S

Post a Response