PHP | DOMElement setAttributeNodeNS() Function

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Â
// Create a new DOMDocument$dom = new DOMDocument();Â
// Create a element with a namespace$root = $dom->createElementNS("my_namepsace", "root");Â Â // Create an element$node = $dom->createElement("div", "zambiatek");Â Â // Append the child$dom->appendChild($root);Â
// Add the node to the dom$newnode = $dom->appendChild($node);Â
// Create a DOMAttr instance$attr = new DOMAttr('style', 'color: green; font-size: 100px;');Â
// Set the attribute$newnode->setAttributeNodeNS($attr);Â Â echo $dom->saveXML();?> |
Output: 
php
<?phpÂ
// Create a new DOMDocument$dom = new DOMDocument();Â Â // Load the XML$dom->loadXML("<?xml version=\"1.0\"?><root>Â Â Â Â <html>Â Â Â Â Â Â Â Â <h1 id=\"my_id\"> Geeksforzambiatek </h1>Â Â Â Â Â Â Â Â <h2> Second heading </h2>Â Â Â Â </html></root>");Â Â // Get the elements$node = $dom->getElementsByTagName('h1')[0];Â Â Â echo "Before the addition of attributes: <br>";Â Â // Get the attribute count$attributeCount = $node->attributes->count();echo 'No of attributes => ' . $attributeCount;Â Â Â // Create a DOMAttr instance$attr = new DOMAttr('class', 'value');Â Â // Add the new attribute$node->setAttributeNodeNS($attr);Â Â Â echo "<br>After the addition of attributes: <br>";Â Â Â // Get the attribute count$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



