Voting

: zero minus zero?
(Example: nine)

The Note You're Voting On

simlee at indiana dot edu
20 years ago
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( "" );
        }
    }
?>

<< Back to user notes page

To Top