Search code examples
phpxmldomdomdocumentdoctype

Add DocType to exits DOMDocument


i have a Php class likes "Extension_DOMDocument" and this extends the PHP "DOMDocument" class.

I create a new Object of Extension_DOMDocument and would add to DocType to this Object.

My code is:

// $this->data is an array to convert array to xml 
$objcDom = new Extension_DOMDocument('1.0', 'utf-8'); 
$objcDom->fromMixed($this->data);

How I can add an DocType to $objcDom?


Solution

  • You can use the the DOM implementation to create a document type object. Document type objects are still DOM nodes. You can append them to an existing document.

    class MyDOMDocument extends DOMDocument {}
    
    $dom = new MyDOMDocument();
    $implementation = new DOMImplementation();
    $dom->appendChild($implementation->createDocumentType('example'));
    $dom->appendChild($dom->createElement('foo'));
    
    echo $dom->saveXml();
    

    Output:

    <?xml version="1.0"?>
    <!DOCTYPE example>
    <foo/>