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:
<?php
$document = new DOMDocument();
$xml = <<<XML
<?xml version= "1.0" encoding= "utf-8" ?>
<content>
Hello World
</content>
XML;
$document ->loadXML( $xml );
$xpath = new DOMXPath( $document );
$tbody = $document ->
getElementsByTagName( 'content' )->item(0);
$query = '//content' ;
$entries = $xpath ->evaluate( $query , $tbody );
echo $entries [0]->nodeValue;
?>
|
Output:
Hello World
Example 2:
<?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 = 'count(//content)' ;
$entries = $xpath ->evaluate( $query , $tbody );
echo $entries ;
?>
|
Output:
3
Reference: https://www.php.net/manual/en/domxpath.construct.php
Last Updated :
17 Mar, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...