PHP | DOMElement getAttributeNode() Function

The DOMElement::getAttributeNode() function is an inbuilt function in PHP which is used to get the attribute node with name, for the current element.

Syntax:

DOMAttr DOMElement::getAttributeNode( string $name )

Parameters: This function accepts a single parameter $name which holds the name of the attribute.



Return Value: This function returns an DOMAttr value containing the attribute node.

Below examples illustrate the DOMElement::getAttributeNode() 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>
    <div attr=\"value\"> DIV 1 </div>
</body>");
  
// Get the elements by tagname
$elements = $dom->getElementsByTagName('div');
  
// Get the attribute node
$node = $elements[0]->getAttributeNode('attr');
  
// Extract name
$name = $node->name;
  
// Extract value
$value = $node->value;
  
echo $name . " => " . $value . "<br>";
?>

chevron_right


Output:

attr => 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\"?>
<body>
    <div id=\"div1\"> DIV 1 </div>
    <div id=\"div2\"> DIV 2 </div>
    <div id=\"div3\"> DIV 3 </div>
</body>");
  
// Get the elements by tagname
$elements = $dom->getElementsByTagName('div');
  
// Get the id of a element
echo "All the divs with id values are: <br>";
foreach ($elements as $element) {
    // Get the attribute node
    $node = $element->getAttributeNode('id');
  
    // Extract name
    $name = $node->name;
  
    // Extract value
    $value = $node->value;
      
    echo $name . " => " . $value . "<br>";
}
?>

chevron_right


Output:

All the divs with id values are:
id => div1
id => div2
id => div3

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