PHP | DOMNamedNodeMap item() function
Last Updated :
19 Feb, 2020
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()
<?php
$dom = new DOMDocument();
$dom ->loadXML("<?xml version=\"1.0\"?>
<root>
<html>
<h1 id=\"first\"
class =\"first\" attrib=\"attrib_value\"> Geeksforgeeks </h1>
</html>
</root>");
$node = $dom ->getElementsByTagName( 'h1' )[0];
$attribute1 = $node ->attributes->item(0)->nodeName;
$attribute2 = $node ->attributes->item(1)->nodeName;
$attribute3 = $node ->attributes->item(2)->nodeName;
echo "$attribute1, $attribute2 and $attribute3" ;
?>
|
Output:
id, class and attrib
Program 2: In this example we will get the value of attributes after fetching them using index()
<?php
$dom = new DOMDocument();
$dom ->loadXML("<?xml version=\"1.0\"?>
<root>
<html>
<h1 id=\"first\"
class =\"geeksforgeeks\" attrib=\"attrib_value\"> Geeksforgeeks </h1>
</html>
</root>");
$node = $dom ->getElementsByTagName( 'h1' )[0];
$attribute1 = $node ->attributes->item(0)->nodeValue;
$attribute2 = $node ->attributes->item(1)->nodeValue;
$attribute3 = $node ->attributes->item(2)->nodeValue;
echo "$attribute1, $attribute2 and $attribute3" ;
?>
|
Output:
first, geeksforgeeks and attrib_value
Reference: https://www.php.net/manual/en/domnamednodemap.item.php
Share your thoughts in the comments
Please Login to comment...