Thursday, June 11, 2026
HomeLanguagesPHP | DOMXPath __construct() Function

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
  
// 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
  
// 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

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6896 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS