Just added a new feature to the PHP DOM extension (will be available in PHP 5.2): DOMNode::getNodePath
With this, you can easily get an XPath for any given DOMNode, works also for attributes, text nodes, comments and all other node types. Here's a little example
<?php $xml = '<foo> <bar>text</bar> <bar foo="bar">more text</bar> <!-- comment --> </foo> '; $dom = new domdocument(); $dom->loadXML($xml); $n = $dom->documentElement->firstChild->nextSibling; $n2 = $n->nextSibling->nextSibling; print $n->getNodePath() ."n"; print $n2->getNodePath() ."n"; print $n2->getAttributeNode("foo")->getNodePath() ."n"; print $n2->firstChild->getNodePath() ."n"; print $n2->nextSibling->nextSibling->getNodePath() ."n";
Which results in:
/foo/bar /foo/bar /foo/bar/@foo /foo/bar/text() /foo/comment()
It's basically just a simple wrapper for xmlGetNodePath from libxml2, maybe useful for some other people also.
BTW, I plan to write more about some new XML features, which are coming with PHP 5.2. It's not very much, but nevertheless interesting (Already a big thanks to Rob for his work)
Update: What will be new in PHP 5.2 in general can be seen here, somehow :)