Php 将DocType添加到文档中

Php 将DocType添加到文档中,php,xml,dom,domdocument,doctype,Php,Xml,Dom,Domdocument,Doctype,我有一个类似于“Extension_DOMDocument”的Php类,它扩展了Php的“DOMDocument”类 我创建了一个扩展名为_DOMDocument的新对象,并将其添加到该对象的DocType中 我的代码是: // $this->data is an array to convert array to xml $objcDom = new Extension_DOMDocument('1.0', 'utf-8'); $objcDom->fromMixed($this

我有一个类似于“Extension_DOMDocument”的Php类,它扩展了Php的“DOMDocument”类

我创建了一个扩展名为_DOMDocument的新对象,并将其添加到该对象的DocType中

我的代码是:

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

如何将DocType添加到
$objcDom

您可以使用DOM实现创建文档类型对象。文档类型对象仍然是DOM节点。您可以将它们附加到现有文档中

class MyDOMDocument extends DOMDocument {}

$dom = new MyDOMDocument();
$implementation = new DOMImplementation();
$dom->appendChild($implementation->createDocumentType('example'));
$dom->appendChild($dom->createElement('foo'));

echo $dom->saveXml();
输出:

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

我会用这个

 <?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();

?>

检查: