pet21
pet21

Reputation: 33

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?

Upvotes: 3

Views: 5193

Answers (2)

Nuri Ensing
Nuri Ensing

Reputation: 2030

I would use this

 <?php

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp->createDocument("", "", $dtd);

// Set other properties
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Create an empty element
$element = $dom->createElement('graph');

// Append the element
$dom->appendChild($element);

// Retrieve and print the document
echo $dom->saveXML();

?>

Check: http://php.net/manual/en/domimplementation.createdocumenttype.php

Upvotes: 2

ThW
ThW

Reputation: 19482

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/>

Upvotes: 5

Related Questions