簡體   English   中英

讓PHP的XMLReader不會在無效文檔中拋出php錯誤

[英]Getting PHP's XMLReader to not throw php errors in invalid documents

我正在編寫解析器,並嘗試使用異常進行良好的錯誤處理。

以下示例代碼:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<rootElem>
XML;

$reader = new XMLReader();
$reader->xml($xml, null, LIBXML_NOERROR | LIBXML_NOWARNING);

$reader->read();

發出:

PHP Warning:  XMLReader::read(): An Error Occured while reading in /Users/evert/code/xml/errortest.php on line 11
PHP Stack trace:
PHP   1. {main}() /Users/evert/code/xml/errortest.php:0
PHP   2. XMLReader->read() /Users/evert/code/xml/errortest.php:11

增加:

libxml_use_internal_errors(true);

沒有效果。

我的目標是稍后檢查錯誤(使用libxml_get_errors() ),並拋出異常。 我覺得唯一的解決方案是使用沉默( @ )運算符,但這似乎是一個壞主意..

注意,當我沒有傳遞LIBXML常量,也沒有使用libxml_use_internal_errors ,我得到一個不同的錯誤,例如:

PHP Warning:  XMLReader::read(): /Users/evert/code/xml/:2: parser error : Extra content at the end of the document in /Users/evert/code/xml/errortest.php on line 11

這表明底層的libxml庫確實壓制了錯誤,但是在XMLReader中,無論如何都會拋出錯誤。

看起來除了使用@之外沒有辦法抑制警告,因為read() php源代碼如下:

retval = xmlTextReaderRead(intern->ptr);
if (retval == -1) {
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "An Error Occured while reading");
    RETURN_FALSE;
} else {
    RETURN_BOOL(retval);
}

因此, libxml_use_internal_errors(true);僅抑制xmlTextReaderRead()中的實際解析錯誤libxml_use_internal_errors(true); 或傳遞給XMLReader::xml()的選項。

從我理解的XMLReader,到驗證文件,必須通過所有文件進行一次完整的傳遞。

我在做的是:

// Enable internal libxml errors
libxml_use_internal_errors(true);
$xml = new \XMLReader();
$xsd='myfile.xsd';
$xml->open('myfile.xml');
$xml->setSchema ($xsd);

// Conduct full pass through document. The only reason is to force validation.
while (@$xml->read()) { }; // empty loop

if (count(libxml_get_errors ())==0) {
    echo "provided xml is well formed and xsd-valid";
    // Now you can start processing without @ as document was validated against xsd and is xml-wellformed
}
else 
    echo "provided xml is wrong and/or not xsd-valid. stopping";

當然,您可以檢查空循環內部的錯誤,然后在第一次錯誤后立即中斷。 我注意到XMLReader在第一次出錯后沒有完全失敗 - 它會繼續並帶來一系列有用的問題。 在第一個問題之后打印出所有發現的問題而不是中斷處理可能是有用的。

我最關心的是XMLReader中存在isValid函數:)我認為這實際上是一種解決方法,但它在處理匹配95%的XMLReader用例之前非常有效並且驗證,因為它用於大型xml集合處理。

暫無
暫無

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

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