The DOMElement::setAttribute() function is an inbuilt function in PHP which is used to set an attribute with given name to the given value. If the attribute does not exist, it will be created.
Syntax:
DOMAttr DOMElement::setAttribute( string $name, string $value )
Parameters: This function accepts two parameters as mentioned above and described below:
- $name: It specifies the name of attribute.
- $value: It specifies the value of attribute.
Return Value: This function returns DOMAttr on success or FALSE on error.
Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly.
Below given programs illustrate the DOMElement::setAttribute() function in PHP:
Program 1:
<?php
$dom = new DOMDocument();
$node = $dom ->createElement( "p" ,
'Hello, this is my paragraph.' );
$newnode = $dom ->appendChild( $node );
$newnode ->setAttribute( "style" , "color:red" );
echo $dom ->saveXML();
?>
|
Output:
<?xml version="1.0"?>
<p style="color:red">Hello, this is my paragraph.</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 ;
$node ->setAttribute( 'new' , 'value' );
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.setattribute.php
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Mar, 2020
Like Article
Save Article