The DOMElement::setIdAttribute() function is an inbuilt function in PHP which is used to declare the attribute specified by name to be of type ID.
Syntax:
php
Output: Press Ctrl+U to see the DOM.
Example 2:
php
Output:
void DOMElement::setIdAttribute( string $name, bool $isId )Parameters: This function accepts two parameters as mentioned above and described below:
- $name: It specifies the name of the attribute.
- $isId: It specifies whether if you want name to be of type ID.
<?php
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
// Enable validate on parse
$dom->validateOnParse = true;
// Create a div element
$element = $dom->appendChild(new DOMElement('div'));
// Create a id attribute to div
$attr = $element->setAttributeNode(new DOMAttr('id',
'geeksforgeeks'));
// Set that attribute as id
$element->setIDAttribute('id', true);
echo $dom->saveXML();
?>
Example 2:
<?php
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
// Enable validate on parse
$dom->validateOnParse = true;
// Create a div element
$element = $dom->appendChild(new DOMElement('div',
'GEEKSFORGEEKS'));
// Create a id attribute to div
$attr = $element->setAttributeNode(new DOMAttr('id',
'geeksforgeeks'));
// Set that attribute as id
$element->setIDAttribute('id', true);
// Get the text of element with id='geeksforgeeks'
// just to see if it works
$value = $dom->getElementById('geeksforgeeks')->textContent;
echo $value;
?>
GEEKSFORGEEKSReference: https://www.php.net/manual/en/domelement.setidattribute.php