簡體   English   中英

如何在PHP中使用schemaValidate()驗證XML時將警告消息作為字符串獲取?

[英]How to get the warning message as a string when validating XML with schemaValidate() in PHP?

我有這個代碼來驗證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); 

如果只需要打印,則可以定義自定義錯誤處理程序以打印錯誤。

這是我怎么做的:

$errs = [ ];
set_error_handler ( function ($severity, $message, $file, $line) use (&$errs) {
    $errs [] = $message;
} );
$validated = $domd->schemaValidate ( 'factinv-3-0.xsd' );
restore_error_handler ();

錯誤描述現在是$ errs,如果有的話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM