Tuesday, November 19, 2024
Google search engine
HomeLanguagesPHP | DOMNamedNodeMap getNamedItem() Function

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.




<?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\"> 
         Geeksforneveropen 
        </h1>
    </html>
</root>");
    
// Get the elements
$node = $dom->getElementsByTagName('h1')[0];
    
// Get the attribute value
$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
   
// Create a new DOMDocument
$dom = new DOMDocument();
     
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <html>
        <h1 id=\"first\" 
            class=\"first\">
         Geeksforneveropen 
        </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;
?>


Output:

Before:
first
After:
changed

Reference: https://www.php.net/manual/en/domnamednodemap.getnameditem.php

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments