PHP | DOMXPath evaluate() Function
Last Updated :
13 Jul, 2021
The DOMXPath::evaluate() function is an inbuilt function in PHP which is used to execute the given XPath expression which is a pattern defined to select a set of nodes.
Syntax:
mixed DOMXPath::evaluate( 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 contextnode for doing relative XPath queries. By default, the queries are relative to the root element.
- $registerNodeNS (Optional): It specifies whether to disable automatic registration of the context node.
Return Value: This function returns TRUE on success.
Exceptions: This function throws DOMXPathException on error.
Below examples illustrate the DOMXPath::evaluate() function in PHP:
Example 1:
php
<?php
$document = new DOMDocument();
$xml = <<<XML
<?xml version= "1.0" encoding= "utf-8" ?>
<bookstore>
<book>
<title lang= "en" >GeeksforGeeks</title>
<price>400</price>
</book>
<book>
<title lang= "en" >Intro to XML</title>
<price>300</price>
</book>
</bookstore>
XML;
$document ->loadXML( $xml );
$xpath = new DOMXPath( $document );
$tbody = $document ->
getElementsByTagName( 'bookstore' )->item(0);
$query = 'count(//title[@lang=\'en\'])' ;
$entries = $xpath ->evaluate( $query , $tbody );
echo "Number of elements with lang = \"en\": $entries\n" ;
?>
|
Output:
Number of elements with lang = "en": 2
Example 2:
php
<?php
$document = new DOMDocument();
$xml = <<<XML
<?xml version= "1.0" encoding= "utf-8" ?>
<GeeksforGeeks>
Keep Learning.
</GeeksforGeeks>
XML;
$document ->loadXML( $xml );
$xpath = new DOMXPath( $document );
$tbody = $document ->
getElementsByTagName( 'GeeksforGeeks' )->item(0);
$query = '//GeeksforGeeks' ;
$entries = $xpath ->evaluate( $query , $tbody );
echo $entries [0]->nodeValue;
?>
|
Output:
Keep Learning.
Reference: https://www.php.net/manual/en/domxpath.evaluate.php
Share your thoughts in the comments
Please Login to comment...