The DOMXPath::__construct() function is an inbuilt function in PHP which is used to create an instance of DOMXPath.
Syntax:
php
Output:
php
Output:
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:
<?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;
?>
Hello WorldExample 2:
<?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;
?>
3Reference: https://www.php.net/manual/en/domxpath.construct.php