PHP | DOMElement getAttributeNodeNS() Function

The DOMElement::getAttributeNodeNS() function is an inbuilt function in PHP which is used to get the attribute node in specific namespace with local name for the current node.
Syntax:
DOMAttr DOMElement::getAttributeNodeNS( string $namespaceURI, string $localName )
Parameters: This function accepts 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 the attribute value containing the attribute node.
Below given programs illustrate the DOMElement::getAttributeNodeNS() function in PHP:
Program 1:
| <?php  Â// Create a new DOMDocument $dom= newDOMDocument();  Â// Load the XML $dom->loadXML("<?xml version=\"1.0\"?> <body xmlns:x=\"my_namespace\">     <x:div x:attr=\"value\" > DIV 1 </x:div> </body>");  Â// Get the elements by tagname $elements= $dom->getElementsByTagName('div');  Â// Get the attribute node $node= $elements[0]->getAttributeNodeNS('my_namespace', 'attr');  Â// Extract name $name= $node->name;  Â// Extract value $value= $node->value;  Âecho$name. " => ". $value. "<br>"; ?>  | 
Output:
attr => value
Program 2:
| <?php  Â// Create a new DOMDocument $dom= newDOMDocument();  Â// Load the XML $dom->loadXML("<?xml version=\"1.0\"?> <root> <body xmlns:x=\"my_namespace1\">     <x:div x:id=\"my_id1\" > DIV 1 </x:div>     <x:div x:id=\"my_id2\" > DIV 1 </x:div> </body> <body xmlns:xi=\"my_namespace2\">     <xi:div xi:id=\"new\" > DIV 1 </xi:div> </body> </root>");  Â// Get the elements by tagname $elements= $dom->getElementsByTagName('div');  Âforeach($elementsas$element) {  Â    $node= $element->getAttributeNodeNS('my_namespace1', 'id');  Â    if($node) {  Â        // Extract name         $name= $node->name;  Â        // Extract value         $value= $node->value;  Â        echo$name. " => ". $value. "<br>";     } } ?>  | 
Output:
id => my_id1 id => my_id2
Reference: https://www.php.net/manual/en/domelement.getattributenodens.php
 
				 
					


