Tuesday, November 19, 2024
Google search engine
HomeLanguagesPHP | DOMXPath query() Function

PHP | DOMXPath query() Function

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
  
// 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);
  
// Get all the element with name content
$query = '//content';
  
// Execute the query
$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
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a XML
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
    <h1>
        Hello
    </h1>
    <h1>
        World
    </h1>
    <h1>
        Foo
    </h1>
    <h1>
        Bar
    </h1>
</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);
  
// Get all the element with name h1
$query = '//h1';
  
// Execute the query
$entries = $xpath->query($query);
  
// Count the number of headings
echo count($entries);
?>


Output:

4

Reference: https://www.php.net/manual/en/domxpath.query.php

RELATED ARTICLES

Most Popular

Recent Comments