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:
<?php
$dom = new DOMDocument();
$node = $dom ->createElement( "p" , 'GeeksforGeeks' );
$newnode = $dom ->appendChild( $node );
$attr = new DOMAttr( 'style' , 'font-size: 80px;' );
$newnode ->setAttributeNode( $attr );
echo $dom ->saveXML();
?>
|
Output:
<?xml version="1.0"?>
<p style="font-size: 80px;">GeeksforGeeks</p>
Program 2:
<?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 ->setAttributeNode( $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.setattributenode.php
Last Updated :
05 Mar, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...