PHP | DOMXPath registerNamespace() Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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";
?>

chevron_right


Output:

0

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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";
?>

chevron_right


Output:

Hello

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.