PHP | DOMNamedNodeMap getNamedItem() Function
Last Updated :
26 Feb, 2020
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
$dom = new DOMDocument();
$dom ->loadXML("<?xml version=\"1.0\"?>
<root>
<html>
<h1 id=\"first\"
class =\"first\"
style=\"color: blue\">
Geeksforgeeks
</h1>
</html>
</root>");
$node = $dom ->getElementsByTagName( 'h1' )[0];
$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
$dom = new DOMDocument();
$dom ->loadXML("<?xml version=\"1.0\"?>
<root>
<html>
<h1 id=\"first\"
class =\"first\">
Geeksforgeeks
</h1>
<h2> Second heading </h2>
</html>
</root>");
$node = $dom ->getElementsByTagName( 'h1' )[0];
echo "Before: <br>" ;
$attribute = $node ->attributes->
getNamedItem( 'class' )->nodeValue;
echo $attribute ;
$node ->setAttribute( 'class' , 'changed' );
echo "<br>After: <br>" ;
$attribute = $node ->attributes->
getNamedItem( 'class' )->nodeValue;
echo $attribute ;
?>
|
Output:
Before:
first
After:
changed
Reference: https://www.php.net/manual/en/domnamednodemap.getnameditem.php
Share your thoughts in the comments
Please Login to comment...