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:
php
Output:
php
Output:
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()
<?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";
?>
id, class and attribProgram 2: In this example we will get the value of attributes after fetching them using index()
<?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";
?>
first, geeksforgeeks and attrib_valueReference: https://www.php.net/manual/en/domnamednodemap.item.php