如何在PHP中使用schemaValidate()验证XML时将警告消息作为字符串获取?

Edw*_*uay 7 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";
}
Run Code Online (Sandbox Code Playgroud)

如果xml文件无效,则说它无效.然而,它无效的原因(例如价格不是整数)仅在PHP警告中给出,我必须禁止它,以便用户不会看到它(使用error_reporting(0)).

我如何获取该消息的文本并将其传递给用户,就像我在C#中使用try/catch一样?

Ste*_*rig 16

我认为你可以使用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); 
Run Code Online (Sandbox Code Playgroud)