PHP | DOMElement getAttributeNS() Function

The DOMElement::getAttributeNS() function is an inbuilt function in PHP which is used to get the value of the attribute in a specific namespace with local name for the current node.

Syntax:

string DOMElement::getAttributeNS( 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 a string value containing the value of attribute, or an empty string if no attribute with the given localName and namespaceURI is found.

Below examples illustrate the DOMElement::getAttributeNS() function in PHP:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// 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 value
$nodeValue = $elements[0]->getAttributeNS('my_namespace', 'attr');
  
echo $nodeValue;
?>

chevron_right


Output:

value

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// 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 ($elements as $element) {
  
    // Get node value only from my_namespace1
    $nodeValue = $element->getAttributeNS('my_namespace1', 'id');
  
    if ($nodeValue) {
       echo $nodeValue . '<br>';
    }
}
?>

chevron_right


Output:

my_id1
my_id2

Reference: https://www.php.net/manual/en/domelement.getattributens.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.