PHP | DOMElement setAttributeNode() Function

The DOMElement::setAttributeNode() function is an inbuilt function in PHP which is used to add a new attribute node to element.

Syntax:

DOMAttr DOMElement::setAttributeNode( DOMAttr $attr )

Parameters: This function accepts a single parameter $attr which holds the attribute node to be added.

Return Value: This function returns an DOMAttr value containing old node if the value has been replaced or NULL.

Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly.



Below given programs illustrate the DOMElement::setAttributeNode() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
   
// Create an element
$node = $dom->createElement("p", 'GeeksforGeeks');
   
// Add the node to the dom
$newnode = $dom->appendChild($node);
   
// Create a DOMAttr instance which
// increase the font-size
$attr = new DOMAttr('style', 'font-size: 80px;');
  
// Set the attribute
$newnode->setAttributeNode($attr);
   
// View the XML
echo $dom->saveXML();
?>

chevron_right


Output:

<?xml version="1.0"?>
<p style="font-size: 80px;">GeeksforGeeks</p>

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <html>
        <h1 id=\"my_id\"> Geeksforgeeks </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->setAttributeNode($attr);
   
echo "<br>After the addition of attributes: <br>";
   
// Get the attribute count
$attributeCount = $node->attributes->count();
echo 'No of attributes => ' . $attributeCount;
?>

chevron_right


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.setattributenode.php




My Personal Notes arrow_drop_up

I love Open Source Culture have contributed to phpMyAdmin, LibreOffice, Ant-Design and Web is my passion

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.