The DOMElement::setIdAttributeNS() function is an inbuilt function in PHP which is used to declare the attribute specified by given local name and namespace URI to be of type ID.
Syntax:
void DOMElement::setIdAttributeNS( string $namespaceURI, string $localName, bool $isId )
Parameters: This function accept three parameters as mentioned above and described below:
- $namespaceURI: It specifies the namespace URI.
- $localName: It specifies the local name.
- $isId: It specifies whether if you want name to be of type ID.
Return Value: This function returns nothing.
Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly or DOM_NOT_FOUND, if name is not an attribute of this element.
Below examples illustrate the DOMElement::setIdAttributeNS() function in PHP:
Example 1:
<?php // Create a new DOMDocument $dom = new DOMDocument(); // Enable validate on parse $dom ->validateOnParse = true; // Create an element $element = $dom ->createElementNS( "my_namespace" , "x:p" , 'Hello, this is my paragraph.' ); // Add the node to the dom $newnode = $dom ->appendChild( $element ); // Set the attribute $newnode ->setAttributeNS( "my_namespace" , "id" , "my_value" ); // Set that attribute as id $element ->setIDAttributeNS( "my_namespace" , 'id' , true); echo $dom ->saveXML(); ?> |
Output: You can press Ctrl+U to see the DOM.
Example 2:
<?php // Create a new DOMDocument $dom = new DOMDocument(); // Enable validate on parse $dom ->validateOnParse = true; // Create an element $element = $dom ->createElementNS( "my_namespace" , "x:p" , 'neveropen' ); // Add the node to the dom $newnode = $dom ->appendChild( $element ); // Set the attribute $newnode ->setAttributeNS( "my_namespace" , "id" , "neveropen" ); // Set that attribute as id $element ->setIDAttributeNS( "my_namespace" , 'id' , true); // Get the text of element with id='neveropen' // just to see if it works $value = $dom ->getElementById( 'neveropen' )->textContent; echo $value ; ?> |
Output:
neveropen
Reference: https://www.php.net/manual/en/domelement.setidattributens.php