在PHP中使用schemaValidate()验证XML时,如何以字符串形式获取警告消息?
我有以下代码来对照XSD文件验证XML文件:在PHP中使用schemaValidate()验证XML时,如何以字符串形式获取警告消息?,php,xml,xsd,Php,Xml,Xsd,我有以下代码来对照XSD文件验证XML文件: $file = 'test.xml'; $schema = 'test.xsd'; $dom = new DOMDocument; $dom->load($file); if ($dom->schemaValidate($schema)) { print "$file is valid.\n"; } else { print "$file is invalid.\n"; } 如果xml文件无效,则表示该文件无效。 但
$file = 'test.xml';
$schema = 'test.xsd';
$dom = new DOMDocument;
$dom->load($file);
if ($dom->schemaValidate($schema)) {
print "$file is valid.\n";
} else {
print "$file is invalid.\n";
}
如果xml文件无效,则表示该文件无效。
但是,它无效的原因(例如,price不是整数)仅在PHP警告中给出,我必须抑制该警告,以便用户看不到它(错误报告(0))
如何获得该消息的文本并将其传递给用户,就像我在C#中使用try/catch所做的那样?如果您只需要打印,您可以定义自定义以打印错误。我认为您可以使用的错误处理功能:
- 切换到用户错误处理
- 从
错误缓冲区检索错误;这将返回一个对象数组libxml
- 清除
错误缓冲区libxml
$file = 'test.xml';
$schema = 'test.xsd';
$dom = new DOMDocument;
$dom->load($file);
libxml_use_internal_errors(true);
if ($dom->schemaValidate($schema)) {
print "$file is valid.\n";
} else {
print "$file is invalid.\n";
$errors = libxml_get_errors();
foreach ($errors as $error) {
printf('XML error "%s" [%d] (Code %d) in %s on line %d column %d' . "\n",
$error->message, $error->level, $error->code, $error->file,
$error->line, $error->column);
}
libxml_clear_errors();
}
libxml_use_internal_errors(false);
我是这样做的:
$errs = [ ];
set_error_handler ( function ($severity, $message, $file, $line) use (&$errs) {
$errs [] = $message;
} );
$validated = $domd->schemaValidate ( 'factinv-3-0.xsd' );
restore_error_handler ();
错误描述现在以$errs(如果有)表示