Skip to content
Related Articles

Related Articles

Improve Article

PHP | DOMXPath registerNamespace() Function

  • Last Updated : 26 Mar, 2020

The DOMXPath::registerNamespace() function is an inbuilt function in PHP which is used to register the namespaceURI and prefix with the DOMXPath object.

Syntax:

bool DOMXPath::registerNamespace( string $prefix,
                    string $namespaceURI )

Parameters: This function accepts two parameters as mentioned above and described below:

  • $prefix: It specifies the prefix.
  • $namespaceURI: It specifies the namespace URI.

Return Value: This function returns TRUE on success or FALSE on failure.

Below given programs illustrate the DOMXPath::registerNamespace() function in PHP:



Program 1:




<?php
  
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a XML
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<body xmlns="geeksforgeeks" >
    <h1>Hello</h1>
</body>
XML;
  
// Load the XML
$document->loadXML($xml);
  
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
  
// Register namespace with prefix
// x and wrong URI
$xpath->registerNamespace('x',
              'geeksforgeeksnew');
  
// Use the prefix to create a query
// to get the text in h1
$query = '//x:body/x:h1/text()';
  
// Execute the query
$entries = $xpath->evaluate($query);
  
// Count the output
echo count($entries) . "\n";
?>

Output:

0

Program 2:




<?php
  
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a XML
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<body xmlns="geeksforgeeks" >
    <h1>Hello</h1>
</body>
XML;
  
// Load the XML
$document->loadXML($xml);
  
// Create a new DOMXPath instance
$xpath = new DOMXPath($document);
  
// Register namespace with prefix x
$xpath->registerNamespace('x',
               'geeksforgeeks');
  
// Use the prefix to create a query
// to get the text in h1
$query = '//x:body/x:h1/text()';
  
// Execute the query
$entries = $xpath->evaluate($query);
  
// View the text
echo $entries->item(0)->nodeValue . "\n";
?>

Output:

Hello

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :