PHP | DOMXPath query() Function
Last Updated :
13 Mar, 2020
The DOMXPath::query() function is an inbuilt function in PHP which is used to evaluate the given XPath expression.
Syntax:
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.
Return Value: This function returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which does not return nodes will return an empty DOMNodeList.
Below given programs illustrate the DOMXPath::query() function in PHP:
Program 1: In this program we will fetch all the element values of elements with name content.
<?php
$document = new DOMDocument();
$xml = <<<XML
<?xml version= "1.0" encoding= "utf-8" ?>
<root>
<content>
First
</content>
<content>
Second
</content>
<content>
Third
</content>
</root>
XML;
$document ->loadXML( $xml );
$xpath = new DOMXPath( $document );
$tbody = $document ->getElementsByTagName( 'root' )->item(0);
$query = '//content' ;
$entries = $xpath ->query( $query );
foreach ( $entries as $entry ) {
echo $entry ->nodeValue . "<br>" ;
}
?>
|
Output:
First
Second
Third
Program 2: In this program we will count all the elements with name h1.
<?php
$document = new DOMDocument();
$xml = <<<XML
<?xml version= "1.0" encoding= "utf-8" ?>
<root>
<h1>
Hello
</h1>
<h1>
World
</h1>
<h1>
Foo
</h1>
<h1>
Bar
</h1>
</root>
XML;
$document ->loadXML( $xml );
$xpath = new DOMXPath( $document );
$tbody = $document ->getElementsByTagName( 'root' )->item(0);
$query = '//h1' ;
$entries = $xpath ->query( $query );
echo count ( $entries );
?>
|
Output:
4
Reference: https://www.php.net/manual/en/domxpath.query.php
Share your thoughts in the comments
Please Login to comment...