Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中使用schemaValidate()验证XML时,如何以字符串形式获取警告消息?_Php_Xml_Xsd - Fatal编程技术网

在PHP中使用schemaValidate()验证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文件无效,则表示该文件无效。 但

我有以下代码来对照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文件无效,则表示该文件无效。 但是,它无效的原因(例如,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(如果有)表示