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:
php
Output:
Program 2:
php
Output:
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.
<?php
// Create a new DOMDocument
$dom = new DOMDocument();
// Create an element
$node = $dom->createElement("p",
'Hello, this is my paragraph.');
// Add the node to the dom
$newnode = $dom->appendChild($node);
// Set the attribute
$newnode->setAttribute("style", "color:red");
echo $dom->saveXML();
?>
<?xml version="1.0"?> <p style="color:red">Hello, this is my paragraph.</p>
Program 2:
<?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;
// Set the id attribute
$node->setAttribute('new', 'value');
echo "<br>After the addition of attributes: <br>";
// Get the attribute count
$attributeCount = $node->attributes->count();
echo 'No of attributes => ' . $attributeCount;
?>
Before the addition of attributes: No of attributes => 1 After the addition of attributes: No of attributes => 2Reference: https://www.php.net/manual/en/domelement.setattribute.php