PHP | DOMXPath __construct() Function

The DOMXPath::__construct() function is an inbuilt function in PHP which is used to create an instance of DOMXPath.

Syntax:

bool DOMXPath::__construct( DOMDocument $doc )

Parameters: This function accepts a single parameter $doc which holds the DOMDocument associated with the DOMXPath.



Below examples illustrate the DOMXPath::__construct() function in PHP:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a XML
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<content>
  Hello World
</content>
XML;
  
// Load the XML
$document->loadXML($xml);
  
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
  
// Get the element
$tbody = $document->
getElementsByTagName('content')->item(0);
  
// Get the element with name content
$query = '//content';
  
// Evaluate the query
$entries = $xpath->evaluate($query, $tbody);
echo $entries[0]->nodeValue;
?>

chevron_right


Output:

Hello World

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a XML
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
    <content>
        First
    </content>
    <content>
        Second
    </content>
    <content>
        Third
    </content>
</root>
XML;
  
// Load the XML
$document->loadXML($xml);
  
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
  
// Get the root element
$tbody = $document->
getElementsByTagName('root')->item(0);
  
// Count the number of element with 
// name content
$query = 'count(//content)';
  
// Evaluate the query
$entries = $xpath->evaluate($query, $tbody);
echo $entries;
?>

chevron_right


Output:

3

Reference: https://www.php.net/manual/en/domxpath.construct.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.