Open In App

PHP | DOMXPath __construct() Function

Last Updated : 17 Mar, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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
<?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;
?>
Output:
Hello World
Example 2: php
<?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;
?>
Output:
3
Reference: https://www.php.net/manual/en/domxpath.construct.php

Next Article

Similar Reads