PHP | DOMNamedNodeMap getNamedItemNS() function
Last Updated :
19 Feb, 2020
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
$dom = new DOMDocument();
$node = $dom ->createElementNS(
"my_namespace" , "x:p" , 'Hello, this is my paragraph.' );
$newnode = $dom ->appendChild( $node );
$newnode ->setAttributeNS( "my_namespace" , "style" , "color:blue" );
echo "<b>Attributes with my_namespace as namespace:</b> <br>" ;
$attribute =
$node ->attributes->getNamedItemNS( 'my_namespace' , 'style' )->nodeValue;
echo $attribute ;
echo "<br><b>Attributes with other_namespace as namespace:</b> <br>" ;
$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
$dom = new DOMDocument();
$node = $dom ->createElementNS( "my_namespace" , "x:p" , 'GeeksforGeeks' );
$newnode = $dom ->appendChild( $node );
$newnode ->setAttributeNS( "my_namespace" , "style" , "color:blue" );
echo "<b>Before:</b> <br>" ;
$attribute =
$node ->attributes->getNamedItemNS( 'my_namespace' , 'style' )->nodeValue;
echo $attribute ;
$newnode ->setAttributeNS( "my_namespace" , "style" , "color:red" );
echo "<br><b>After:</b> <br>" ;
$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
Share your thoughts in the comments
Please Login to comment...