PHP | DOMNode getNodePath() Function

The DOMNode::getNodePath() function is an inbuilt function in PHP which is used to get an XPath location path for the node.

Syntax:

string DOMNode::getNodePath( void )

Parameters: This function doesn’t accept any parameters.



Return Value: This function returns a string containing the XPath, or NULL in case of an error.

Below examples illustrate the DOMNode::getNodePath() function in PHP:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument instance
$dom = new DOMDocument;
  
// Load the XML
$dom->loadXML('
<root>
    <h1>GeeksforGeeks</h1>
</root>
');
  
// Print XPath of the element
echo $dom->getElementsByTagName('h1')
    ->item(0)->getNodePath();
?>

chevron_right


Output:

/root/h1

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// Create a new DOMDocument instance
$dom = new DOMDocument;
   
// Load the XML
$dom->loadXML('
<root>
    <h1>Geeks</h1>
    <div>
        <h1>For</h1>
    </div>
    <h1>Geeks</h1>
</root>
');
   
// Print XPath of the element
for ($i = 0; $i < 3; $i++) {
  
    // Print where the line where the 'node' 
    // element was defined in
    echo $i+1 . ') The h1 tag\'s Xpath is: ' 
        . $dom->getElementsByTagName('h1')
        ->item($i)->getNodePath() . "<br>";
}
?>

chevron_right


Output:

1) The h1 tag's Xpath is: /root/h1[1]
2) The h1 tag's Xpath is: /root/div/h1
3) The h1 tag's Xpath is: /root/h1[2]

Reference: https://www.php.net/manual/en/domnode.getnodepath.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.