我有一个快速函数来加载 XML 字符串,并根据模式对其进行验证。当其给定格式良好的 XML 时,它的行为非常完美。
然而,当我搞砸了 xml 语法本身时,php 会抛出一个 fatal error 并终止脚本。我正在检查 loadXML 函数返回值,我想要一个简单的 true/false。如果 xml 是脏的,loadXML() 将失败,我可以简单地返回验证失败。我已经尝试设置一个空的错误处理程序,但它仍然会终止脚本。
有什么想法吗?我需要降级错误还是什么?
包含的引用代码 (PHP):
function __maskerrors(){};
function ValidateImageXML($xml_string)
{
/* Parse XML data string into DOM object */
$xdoc = new DomDocument;
/* Calculate schema location */
$schema = dirname(realpath(__FILE__));
$schema.= "/image-xml-schema.xsd";
/* Mask any errors */
set_error_handler('__maskerrors');
/* Parse xml string, check for success */
if($xdoc->loadXML($xml_string))
{
/* Validate xml against schema */
if($xdoc->schemaValidate($schema))
{
/* Valid XML structure & valid against schema, return true */
return true;
}
else
{
/* Valid XML structure, but invalid against schema. Return false */
return false;
}
}
else
{
/* Invalid XML structure, return false */
return false;
}
/* Stop masking errors */
restore_error_handler();
}
最佳答案
尝试
libxml_use_internal_errors(true);
$xdoc->loadXml($yourXml);
libxml_clear_errors();
return $xdoc->schemaValidate($schema)
这将禁用 libxml 错误并允许用户根据需要获取错误信息(或清除它们)
关于PHP XML 验证在传递错误 XML 时抛出致命异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7222753/