$dom = new DOMDocument(); $element = $dom->createElement("div"); $element->setAttribute("class", "container"); echo $dom->saveHTML($element);
$dom = new DOMDocument(); $element = $dom->createElement("a"); $element->setAttribute("href", "https://www.example.com"); $element->setAttribute("target", "_blank"); echo $dom->saveHTML($element);In this example, a new anchor tag element is added to the DOM and two attributes, href and target, are set with their respective values. The HTML output of this code would be ``. The PHP DOMElement setAttribute method is a part of the PHP DOM library, which is included in the core PHP package.