phpxmldomdom-node

How to create a DOMNode in PHP?


The class DOMNode doesn't provide a contructor and also no static methods like createInstance(). So, how to create an DOMNode instance?


Solution

  • Create a DOMDocument. It extends from DOMNode, has a constructor, and represents the rootnode of a document. Being a DOMNode, DOMDocument has methods for adding children. For instance, DOMDocument has a method CreateElement, which returns a DOMElement, which also inherits from DOMNode.
    All in all, it seems that DOMNode is just the base class and shouldn't be used directly.

    <?php
    
    $dom = new DOMDocument('1.0', 'utf-8');
    
    $element = $dom->createElement('test', 'This is the root element!');
    
    // We insert the new element as root (child of the document)
    $dom->appendChild($element);
    
    echo $dom->saveXML();
    ?>
    

    (Example taken from the CreateElement documentation)