The DOMXPath::query() function is an inbuilt function in PHP which is used to evaluate the given XPath expression.
Syntax:
php
Output:
php
Output:
DOMNodeList DOMXPath::query( string $expression,
DOMNode $contextnode, bool $registerNodeNS )
Parameters: This function accept three parameters as mentioned above and described below:
- $expression: It specifies the XPath expression to execute.
- $contextnode (Optional): It specifies the optional contextnode for doing relative XPath queries. By default, the queries are relative to the root element.
- $registerNodeNS (Optional): It specifies the optional registerNodeNS to disable automatic registration of the context node.
<?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);
// Get all the element with name content
$query = '//content';
// Execute the query
$entries = $xpath->query($query);
foreach ($entries as $entry) {
echo $entry->nodeValue . "<br>";
}
?>
First Second ThirdProgram 2: In this program we will count all the elements with name h1.
<?php
// Create a new DOMDocument instance
$document = new DOMDocument();
// Create a XML
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
<h1>
Hello
</h1>
<h1>
World
</h1>
<h1>
Foo
</h1>
<h1>
Bar
</h1>
</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);
// Get all the element with name h1
$query = '//h1';
// Execute the query
$entries = $xpath->query($query);
// Count the number of headings
echo count($entries);
?>
4Reference: https://www.php.net/manual/en/domxpath.query.php