PHP | DOMElement setAttributeNodeNS() Function
Last Updated :
21 Jun, 2022
The DOMElement::setAttributeNodeNS() function is an inbuilt function in PHP which is used to add a new attribute node to element. This is just an alternative for setAttributeNode() function.
Syntax:
DOMAttr DOMElement::setAttributeNodeNS( DOMAttr $attr )
Parameters: This function accepts a single parameter $attr which holds the attribute to be added.
Return Value: This function returns the old node if the attribute has been replaced.
Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly.
Below examples illustrate the DOMElement::setAttributeNodeNS() function in PHP:
Example 1:
php
<?php
$dom = new DOMDocument();
$root = $dom ->createElementNS("my_namepsace", "root");
$node = $dom ->createElement("div", "GeeksforGeeks");
$dom ->appendChild( $root );
$newnode = $dom ->appendChild( $node );
$attr = new DOMAttr( 'style' , 'color: green; font-size: 100px;' );
$newnode ->setAttributeNodeNS( $attr );
echo $dom ->saveXML();
?>
|
Output: Example 2:
php
<?php
$dom = new DOMDocument();
$dom ->loadXML("<?xml version=\"1.0\"?>
<root>
<html>
<h1 id=\"my_id\"> Geeksforgeeks </h1>
<h2> Second heading </h2>
</html>
</root>");
$node = $dom ->getElementsByTagName( 'h1' )[0];
echo "Before the addition of attributes: <br>";
$attributeCount = $node ->attributes-> count ();
echo 'No of attributes => ' . $attributeCount ;
$attr = new DOMAttr( 'class' , 'value' );
$node ->setAttributeNodeNS( $attr );
echo "<br>After the addition of attributes: <br>";
$attributeCount = $node ->attributes-> count ();
echo 'No of attributes => ' . $attributeCount ;
?>
|
Output:
Before the addition of attributes:
No of attributes => 1
After the addition of attributes:
No of attributes => 2
Reference: https://www.php.net/manual/en/domelement.setattributenodens.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...