note 60188 added to ref.dom
| From: | simlee at indiana dot edu | Date: | Thu, 29 Dec 2005 08:16:03 +0000 |
| Subject: | note 60188 added to ref.dom | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-100898@lists.php.net to get a copy of this message | ||
The project I'm currently working on uses XPaths to dynamically navigate through chunks of an
XML file. I couldn't find any PHP code on the net that would build the XPath to a node for me,
so I wrote my own function. Turns out it wasn't as hard as I thought it might be (yay
recursion), though it does entail using some PHP shenanigans...
Hopefully it'll save someone else the trouble of reinventing this wheel.
<?php
function getNodeXPath( $node ) {
// REMEMBER THAT XPATHS USE BASE-1 INSTEAD OF BASE-0!!!
// Get the index for the current node by looping through the siblings.
$parentNode = $node->parentNode;
if( $parentNode != null ) {
$nodeIndex = 0;
do {
$testNode = $parentNode->childNodes->item( $nodeIndex );
$nodeName = $testNode->nodeName;
$nodeIndex++;
// PHP trickery! Here we create a counter based on the node
// name of the test node to use in the XPath.
if( !isset( $$nodeName ) ) $$nodeName = 1;
else $$nodeName++;
// Failsafe return value.
if( $nodeIndex > $parentNode->childNodes->length ) return( "/" );
} while( !$node->isSameNode( $testNode ) );
// Recursively get the XPath for the parent.
return( getNodeXPath( $parentNode ) . "/{$node->nodeName}[{$$nodeName}]" );
} else {
// Hit the root node! Note that the slash is added when
// building the XPath, so we return just an empty string.
return( "" );
}
}
?>
----
Manual Page -- http://www.php.net/manual/en/ref.dom.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+60188
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60188&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60188&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60188&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60188&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60188&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60188&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60188&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+60188&report=yes
Search -- http://master.php.net/manage/user-notes.php