Open In App

PHP | DOMNamedNodeMap getNamedItemNS() function

Last Updated : 19 Feb, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
The DOMNamedNodeMap::getNamedItemNS() function is an inbuilt function in PHP which is used to retrieve a node with a specific local name and namespace URI. This function can be used to get the value of a attribute from a specific namespace. Syntax:
DOMNode DOMNamedNodeMap::getNamedItemNS
( string $namespaceURl, string $localName )
Parameters: This function accepts two parameters as mentioned above and described below:
  • $namespaceURl: It specifies the namespace URI.
  • $localName: It specifies the local name.
Return Value: This function returns a node with given local name and namespace URI. Below given programs illustrate the DOMNamedNodeMap::getNamedItemNS() function in PHP: Program 1: In this example, we will get the attribute value of a element with two different namespaces. php
<?php
// Create a new DOMDocument
$dom = new DOMDocument();

// Create an element with namespace
$node = $dom->createElementNS(
   "my_namespace", "x:p", 'Hello, this is my paragraph.');

// Add the node to the dom
$newnode = $dom->appendChild($node);

// Set the attribute with a namespace
$newnode->setAttributeNS("my_namespace", "style", "color:blue");

echo "<b>Attributes with my_namespace as namespace:</b> <br>";

// Get the attribute value
$attribute = 
   $node->attributes->getNamedItemNS('my_namespace', 'style')->nodeValue;
echo $attribute;

echo "<br><b>Attributes with other_namespace as namespace:</b> <br>";

// Get the attribute value
$attribute = 
   $node->attributes->getNamedItemNS('other_namespace', 'style')->nodeValue;
echo $attribute;
?>
Output:
Attributes with my_namespace as namespace:
color:blue
Attributes with other_namespace as namespace:
// Empty string means no attributes found.
Program 2: In this example we will check if the function fetches the latest attribute values or not by altering the value of attribute. php
<?php
// Create a new DOMDocument
$dom = new DOMDocument();

// Create an element
$node = $dom->createElementNS("my_namespace", "x:p", 'GeeksforGeeks');

// Add the node to the dom
$newnode = $dom->appendChild($node);

// Set the attribute with a namespace
$newnode->setAttributeNS("my_namespace", "style", "color:blue");

echo "<b>Before:</b> <br>";

// Get the attribute value
$attribute = 
    $node->attributes->getNamedItemNS('my_namespace', 'style')->nodeValue;
echo $attribute;

// Change the attribute value 
$newnode->setAttributeNS("my_namespace", "style", "color:red");

echo "<br><b>After:</b> <br>";

// Get the attribute value
$attribute = 
    $node->attributes->getNamedItemNS('my_namespace', 'style')->nodeValue;
echo $attribute;
?>
Output:
Before:
color:blue
After:
color:red
Reference: https://www.php.net/manual/en/domnamednodemap.getnameditemns.php

Next Article

Similar Reads