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.

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>
    <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;
?>

chevron_right


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.

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>
    <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;
?>

chevron_right


Output:

Before:
first
After:
changed

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