在没有声明DOCTYPE的情况下针对DTD外部文件验证XML

时间:2014-08-12 23:41:56

标签: php xml validation external dtd

我有外部XML和DTD文件。遗憾的是,XML文件没有声明指向其对应的DTD文件。是否有可能仍然使用PHP验证它?任何帮助或资源的链接将不胜感激。感谢。

1 个答案:

答案 0 :(得分:2)

重复XML validation against given DTD in PHP

<?php

$xml = <<<END
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE foo SYSTEM "foo.dtd">
<foo>
    <bar>baz</bar>
</foo>
END;

$root = 'foo';

$old = new DOMDocument;
$old->loadXML($xml);

$creator = new DOMImplementation;
$doctype = $creator->createDocumentType($root, null, 'bar.dtd');
$new = $creator->createDocument(null, null, $doctype);
$new->encoding = "utf-8";

$oldNode = $old->getElementsByTagName($root)->item(0);
$newNode = $new->importNode($oldNode, true);
$new->appendChild($newNode);

$new->validate();

?>