PHP | DOMNamedNodeMap item() function

The DOMNamedNodeMap::item() function is an inbuilt function in PHP which is used to retrieve a node specified by index. This function is used to get a specific attribute from an element and further we can get the name or value of that attribute as per requirements.

Syntax:

DOMNamedNodeMap DOMNamedNodeMap::item( int $index )

Parameters:This function accepts a single parameter $index which holds the index.

Return Value: This function returns a node at the index’th position in the map.

Below given programs illustrate the DOMNamedNodeMap::item() function in PHP:
Program 1: In this example, we will get the name of attributes after fetching them using index()



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\" attrib=\"attrib_value\"> Geeksforgeeks </h1>
    </html>
</root>");
    
// Get the elements
$node = $dom->getElementsByTagName('h1')[0];
    
// Get the 2nd attribute's value
$attribute1 = $node->attributes->item(0)->nodeName;
$attribute2 = $node->attributes->item(1)->nodeName;
$attribute3 = $node->attributes->item(2)->nodeName;
echo "$attribute1, $attribute2 and $attribute3";
?>

chevron_right


Output:

id, class and attrib

Program 2: In this example we will get the value of attributes after fetching them using index()

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=\"geeksforgeeks\" attrib=\"attrib_value\"> Geeksforgeeks </h1>
    </html>
</root>");
    
// Get the elements
$node = $dom->getElementsByTagName('h1')[0];
    
// Get the 2nd attribute's value
$attribute1 = $node->attributes->item(0)->nodeValue;
$attribute2 = $node->attributes->item(1)->nodeValue;
$attribute3 = $node->attributes->item(2)->nodeValue;
echo "$attribute1, $attribute2 and $attribute3";
?>

chevron_right


Output:

first, geeksforgeeks and attrib_value

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