gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:46:38 28 4
gpt4 key购买 nike

我有这段代码可以根据 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文件无效,那么就说无效。然而,它无效的原因(例如价格不是整数)仅在 PHP 警告中给出,我必须抑制它以便用户看不到它(使用 error_reporting(0))。

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

最佳答案

我想你可以使用 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);

关于php - 在 PHP 中使用 schemaValidate() 验证 XML 时如何将警告消息作为字符串获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1345744/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com