PHP | DOMDocument registerNodeClass() Function

Last Updated : 20 Feb, 2020
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
<?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
<?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
Comment