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:
php
Output:
php
Output:
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:
<?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>";
?>
attr => valueExample 2:
<?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>";
}
?>
All the divs with id values are: id => div1 id => div2 id => div3Reference: https://www.php.net/manual/en/domelement.getattributenode.php