Open In App

PHP | DOMDocument getElementsByTagnameNS() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The DOMDocument::getElementsByTagNameNS() function is an inbuilt function in PHP which is used to search for all elements with given tag name in specified namespace.

Syntax: 

DOMNodeList DOMDocument::getElementsByTagNameNS( 
            string $namespaceURI, string $localName )

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

  • $namespaceURI: It specifies the namespace URI of the elements to match on and * matches all namespaces.
  • $localName : It specifies the local name of the elements to match on and * matches all local names.

Return Value: This function returns a DOMNodeList of all elements with a given local name and a namespace URI.

Below given programs illustrate the DOMDocument::getElementsByTagNameNS() function in PHP:

Program 1: In this example, we will get localname and prefix of elements with a specific namespace. 

PHP




<?php
// Create an XML
$xml = <<<EOD
<?xml version="1.0" ?>
<!-- this is the namespace -->
<chapter xmlns:xi="my_namespace">
<title>Books of the other guy..</title>
<para>
    <xi:include>
        <xi:fallback>
        </xi:fallback>
    </xi:include>
</para>
</chapter>
EOD;
 
$dom = new DOMDocument;
  
// Load the XML string defined above
$dom->loadXML($xml);
  
// Use getElementsByTagName to get
// the elements from xml
foreach ($dom->getElementsByTagNameNS(
        'my_namespace', '*') as $element) {
    echo '<b>Local name:</b> ',
        $element->localName,
        ', <b>Prefix: </b>',
        $element->prefix, "<br>";
}
 
?>


Output: 

Local name: include, Prefix: xi
Local name: fallback, Prefix: xi

Program 2: In this example, we will get the number of elements of a certain namespace. 

PHP




<?php
// Create an XML
$xml = <<<EOD
<?xml version="1.0" ?>
<!-- this is the namespace -->
<chapter xmlns:xi="my_namespace">
<title>Books of the other guy..</title>
<para>
    <xi:include>        <!--  1st -->
        <xi:fallback>   <!--  2nd -->
        </xi:fallback>
    </xi:include>
    <xi:include>        <!--  3rd -->
        <xi:fallback>   <!--  4th -->
        </xi:fallback>
    </xi:include>
</para>
</chapter>
EOD;
  
$dom = new DOMDocument();
  
// Load the XML string defined above
$dom->loadXML($xml);
  
// It will count all occurrence of
// xi inside my_namespace
$elements = $dom->getElementsByTagNameNS(
            'my_namespace', '*');
 
print_r($elements->length);
?>


Output: 

4

Reference: https://www.php.net/manual/en/domdocument.getelementsbytagnamens.php
 



Last Updated : 07 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads