PHP Conference Nagoya 2025

DOMImplementation::createDocumentType

(PHP 5, PHP 7, PHP 8)

DOMImplementation::createDocumentType Creates an empty DOMDocumentType object

说明

public DOMImplementation::createDocumentType(string $qualifiedName, string $publicId = "", string $systemId = ""): DOMDocumentType|false

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

参数

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

返回值

A new DOMDocumentType node with its ownerDocument set to null or false on error.

错误/异常

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

更新日志

版本 说明
8.0.0 Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

示例

示例 #1 Creating a document with an attached DTD

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

?>

以上示例会输出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

参见

添加备注

用户贡献的备注 1 note

up
0
until-all-bytes-are-free at example dot org
13 years ago
I had problems to use a DTD from a file. It needed to be resolved relatively and it contained characters that made DomDocument failed to resolve the file.

Encoding and an absolute filename did not help much. So I used the data:// streamwrapper ( http://php.net/manual/en/wrappers.data.php ) as a work-around:

<?php

// relative or absolute filename
$path = '...';

// convert file contents into a filename
$data = file_get_contents($path);
$systemId = 'data://text/plain;base64,'.base64_encode($data);

// ...

// Creates a DOMDocumentType instance
$dtd = $aImp->createDocumentType('qualified name', '', $systemId);

?>

Works like a charm.
To Top