Blog Posts

Added DOMNode::getNodePath

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

$xml = '<foo>
            <bar foo="bar">more text</bar>
             <!-- comment -->

$dom = new domdocument();

$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:


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 :)

Related Entries:
- php xslcache extension by the New York Times
- Added xslt profiling to PHP 5.3 and 6 CVS
- Pimp up your XSLT transformation
- Profile XSLT transformations within PHP
- domxml and PHP 5

About the author

Comments [4], 17.07.2006 14:06 CET (Trackback)

Maarten Manders, 19.07.2006 10:07 CET

Very useful, thanks! :)

Rodolfo, 24.04.2010 19:29 CET

It´s very useful indeed. In fact i need it right now.
I have a question, though:
xpaths returned aren´t zero-based...
Why? I think I must be missing something about this, but can not find what is it.

Chregu, 24.04.2010 20:19 CET

XPath indexes always start at 1 and not at zero.

Add a comment

Your email adress will never be published. Comment spam will be deleted!