Tuesday, June 9, 2026
HomeLanguagesPHP | DOMElement setIdAttributeNS() Function

PHP | DOMElement setIdAttributeNS() Function

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

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6895 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS