About the Author
Adam Trachtenberg is the Senior Manager of Platform Evangelism at eBay, where he preaches the gospel of the eBay platform to developers and businessmen around the globe. Before eBay, Adam co-founded and served as vice president for development at two companies, Student.Com and TVGrid.Com. At both firms, he led the front- and middle-end web site design and development. Adam began using PHP in 1997, and is the author of Upgrading to PHP 5 and coauthor of PHP Cookbook, both published by O'Reilly Media. He lives in San Francisco, California, and has a B.A. and M.B.A. from Columbia University.
See All Posts by This Author
September 26th, 2006 •
Related •
Filed Under
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?
Comment by David Sklar on 26 September 2006:
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.
Comment by Adam Trachtenberg on 27 September 2006:
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. :)
Comment by David Sklar on 27 September 2006:
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.
Comment by StephenB on 12 January 2008:
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