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:
php
Output:
php
Output:
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.
<?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;
?>
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
// 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;
?>
Before: color:blue After: color:redReference: https://www.php.net/manual/en/domnamednodemap.getnameditemns.php