我一直在尝试如何在PHP中根据XSD验证XML,但由于缺乏示例,未能做到这一点。我读过is_Valid()等
我在下面举了一个例子,但它不能正常工作。
$reader = new XMLReader();
$reader->open('items.xml');
$reader->setSchema('items.xsd');
//Now how do validate against XSD and print errors here
感谢
我创建了一个性能基准:XMLReader与DOMDocument
XMLReader.php:
$script_starttime = microtime(true);
libxml_use_internal_errors(true);
$xml = new XMLReader;
$xml->open($_FILES["file"]["tmp_name"]);
$xml->setSchema($xmlschema);
while (@$xml->read()) {};
if (count(libxml_get_errors ())==0) {
echo 'good';
} else {
echo 'error';
}
echo '<br><br>Time: ',(microtime(true) - $script_starttime)*1000," ms, Memory: ".memory_get_usage()." bytes";
DOMDocument.php:
$script_starttime = microtime(true);
libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xmlfile = $_FILES["file"]["tmp_name"];
$xml->load($xmlfile);
if ($xml->schemaValidate($xmlschema)) {
echo 'good';
} else {
echo 'error';
}
echo '<br><br>Time: ',(microtime(true) - $script_starttime)*1000," ms, Memory: ".memory_get_usage()." bytes";
我的示例:18 MB xml,258.230行
结果:
XMLReader-656.14199683367毫秒,379064字节
DOMDocument-483.04295539856 ms,369280字节
因此,我决定使用DOMDocument,但只需使用您自己的xml和xsd并使用您更快的选择即可。
我刚刚在这里创建了关于验证的类似答案:获取PHP';s XMLReader不能在无效文档中抛出php错误
但最重要的是,若不传递整个文档,就无法使用XMLReader进行验证。这种情况类似于数据库结果集-您必须在文档节点中迭代(XMLReader的读取方法),并且只有在读取(有时甚至更晚)时才能验证每个节点
首先,使用DOM。它的功能要强大得多,将读者和作者融合在一起——我认为没有理由不这样做。它还有一个更逻辑的接口(IMHO)。
一旦你做到了这一点,DOMDocument::schemaValidate()
就会做你想要做的事情。