Tuesday, June 9, 2026
HomeLanguagesPHP | DOMDocument registerNodeClass() Function

PHP | DOMDocument registerNodeClass() Function

The DOMDocument::registerNodeClass() function is an inbuilt function in PHP which is used to register extended class used to create base node type.

Syntax:

bool DOMDocument::registerNodeClass( string $baseclass,
                              string $extendedclass )

Parameters: This function accept two parameters as mentioned above and described below:

  • $baseclass: It specifies the DOM class that you want to extend.
  • $extendedclass: It specifies the extended class name.

Return Value: This function returns TRUE on success or FALSE on failure.

Below given programs illustrate the DOMDocument::registerNodeClass() function in PHP:

Program 1: In this program we will create a HTML div element with CSS properties using classes.




<?php
  
// Create a class myElement
class myElement extends DOMElement
{
    // Create a custom function to
    // append the element
    public function appendElement($name)
    {
        return $this->appendChild(new myElement($name));
    }
}
  
// Create a class myDocoment
class myDocument extends DOMDocument {
  
    // Create a custom function to set the root
    public function setRoot($name) {
        return $this->appendChild(new myElement($name));
    }
}
  
// Create a instance of above class
$doc = new myDocument();
  
// Register the node class
$doc->registerNodeClass('DOMElement', 'myElement');
  
// Use setRoot created in myDocument class
$root = $doc->setRoot('div');
  
// Use appendElement created in myElement
$child = $root->appendElement('div');
  
// Set the attribute
$child->setAttribute('style',
    'background:blue; width:100px;height:100px');
  
echo $doc->saveXML();
?>


Output:

Program 2: In this program we will get the text content of a tag using classes.




<?php
  
class myElement extends DOMElement {
  
    // Create a custom function to
    // get the value of node
    public function getData() {
        return $this->nodeValue;
    }
}
  
// Create a new DOMDocument
$doc = new DOMDocument;
  
// Load the XML
$doc->loadXML(
"<root><div><h1>This is my heading</h1></div></root>");
  
// Register the node class
$doc->registerNodeClass("DOMElement", "myElement");
  
// Get the element
$element = $doc->getElementsByTagName("h1")->item(0);
  
// Use the custom created getData() function
echo $element->getData();
?>


Output:

This is my heading

Reference: https://www.php.net/manual/en/domdocument.registernodeclass.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