PHP | DOMNamedNodeMap getNamedItem() Function
The DOMNamedNodeMap::getNamedItem() function is an inbuilt function in PHP which is used to retrieve a node specified by name. This is used to get the attribute items and further get information about the attribute.
Syntax:
DOMNode DOMNamedNodeMap::getNamedItem( string $name )
Parameters: This function accepts a single parameter $name which holds the nodeName of the node to retrieve.
Return Value: This function returns DOMNode with the specified name on success.
Below examples illustrate the DOMNamedNodeMap::getNamedItem() function in PHP:
Example 1: In this example we will get the attribute value of a element.
<?php // Create a new DOMDocument$dom = new DOMDocument(); // Load the XML$dom->loadXML("<?xml version=\"1.0\"?><root> <html> <h1 id=\"first\" class=\"first\" style=\"color: blue\"> Geeksforgeeks </h1> </html></root>"); // Get the elements$node = $dom->getElementsByTagName('h1')[0]; // Get the attribute value$attribute = $node->attributes-> getNamedItem('style')->nodeValue;echo $attribute;?> |
Output:
color: blue
Example 2: In this example we will check if the function fetches the latest attribute values or not by altering the value of attribute.
<?php // Create a new DOMDocument$dom = new DOMDocument(); // Load the XML$dom->loadXML("<?xml version=\"1.0\"?><root> <html> <h1 id=\"first\" class=\"first\"> Geeksforgeeks </h1> <h2> Second heading </h2> </html></root>"); // Get the elements$node = $dom->getElementsByTagName('h1')[0]; echo "Before: <br>"; // Get the attribute value$attribute = $node->attributes-> getNamedItem('class')->nodeValue;echo $attribute; // Change the value of attribute$node->setAttribute('class', 'changed'); echo "<br>After: <br>"; // Get the attribute value$attribute = $node->attributes-> getNamedItem('class')->nodeValue;echo $attribute;?> |
Output:
Before: first After: changed
Reference: https://www.php.net/manual/en/domnamednodemap.getnameditem.php


