我有一个快速函数来加载XML字符串,并根据模式验证它。当给定格式良好的XML时,它表现得很好。
但是,当我弄乱xml语法本身时,php抛出致命错误并终止脚本。我正在检查loadXML函数返回值,我想要一个简单的真/假。如果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();
}
Try with
libxml_use_internal_errors(true);
$xdoc->loadXml($yourXml);
libxml_clear_errors();
return $xdoc->schemaValidate($schema)
这将禁用libxml错误,并允许用户在需要时获取错误信息(或清除它们)
见http://.php.net/manual/en/book.libxml.php