The DOMElement::getElementsByTagNameNS() function is an inbuilt function in PHP which is used to get all the descendant elements with a given localName and namespaceURI.
Syntax:
DOMNodeList DOMElement::getElementsByTagNameNS( string $namespaceURI, string $localName )
Parameters: This function accept two parameters as mentioned above and described below:
- $namespaceURI: It specifies the namespace URI.
- $localName: It specifies the local name.
Return Value: This function returns a DOMNodeList value containing all matched elements in the order in which they are encountered in a preorder traversal of this element tree.
Below given programs illustrate the DOMElement::getElementsByTagNameNS() function in PHP:
Program 1:
<?php // Create a new DOMDocument $dom = new DOMDocument(); Â Â Â // Load the XML $dom ->loadXML("<?xml version=\"1.0\"?> <root> Â Â Â Â <div xmlns:x=\"my_namespace\"> Â Â Â Â Â Â Â Â <x:h1 x:style=\"color:red;\"> Â Â Â Â Â Â Â Â Â Â Â Â Hello, this is my red heading. Â Â Â Â Â Â Â Â </x:h1> Â Â Â Â Â Â Â Â <x:h1 x:style=\"color:green;\"> Â Â Â Â Â Â Â Â Â Â Â Â Hello, this is my green heading. Â Â Â Â Â Â Â Â </x:h1> Â Â Â Â Â Â Â Â <x:h1 x:style=\"color:blue;\"> Â Â Â Â Â Â Â Â Â Â Â Â Hello, this is my blue heading. Â Â Â Â Â Â Â Â </x:h1> Â Â Â Â </div> Â Â Â Â <div xmlns:y=\"another_namespace\"> Â Â Â Â Â Â Â Â <y:h1 y:style=\"color:red;\"> Â Â Â Â Â Â Â Â Â Â Â Â Hello, this is my new red heading. Â Â Â Â Â Â Â Â </y:h1> Â Â Â Â Â Â Â Â <y:h1 y:style=\"color:green;\"> Â Â Â Â Â Â Â Â Â Â Â Â Hello, this is my new green heading. Â Â Â Â Â Â Â Â </y:h1> Â Â Â Â Â Â Â Â <y:h1 y:style=\"color:blue;\"> Â Â Â Â Â Â Â Â Â Â Â Â Hello, this is my new blue heading. Â Â Â Â Â Â Â Â </y:h1> Â Â Â Â </div> </root>"); Â Â Â // Get the elements with h1 tag from // specific namespace $nodeList = $dom ->getElementsByTagNameNS( Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'my_namespace' , 'h1' ); Â Â foreach ( $nodeList as $node ) { Â Â Â Â echo $node ->getAttribute( 'x:style' ) . '<br>' ; } ?> |
Output:
color:red;
color:green;
color:blue;
Program 2:
<?php   // Create a new DOMDocument $dom = new DOMDocument();    // Load the XML $dom ->loadXML("<?xml version=\"1.0\"?> <root>     <div xmlns:x=\"my_namespace\">         <x:p>HELLO.</x:p>         <x:p>NEW.</x:p>         <x:p>WORLD.</x:p>     </div>     <div xmlns:y=\"g4g_namespace\">         <y:p>GEEKS</y:p>         <y:p>FOR</y:p>         <y:p>GEEKS</y:p>     </div> </root>");    // Get the elements $nodeList = $dom ->getElementsByTagNameNS(                     'g4g_namespace' , 'p' );   foreach ( $nodeList as $node ) {     echo $node ->textContent . '<br>' ; } ?> |
Output:
GEEKS
FOR
GEEKS
Reference: https://www.php.net/manual/en/domelement.getelementsbytagnamens.php