让 PHP 的 XMLReader 不会在无效文档中抛出 php 错误 [英] Getting PHP's XMLReader to not throw php errors in invalid documents

查看:29
本文介绍了让 PHP 的 XMLReader 不会在无效文档中抛出 php 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写解析器,并尝试对异常进行良好的错误处理.

I'm in the process of writing a parser, and trying to do good error handling with exceptions.

以下示例代码:

<?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()),并抛出异常.我觉得唯一的解决方案是使用静音 (@) 运算符,但这似乎是个坏主意..

My goal is to check errors later (with libxml_get_errors()), and throw an exception. I feel the only solution is the use of the silence (@) operator, but this seems like a bad idea..

请注意,当我不传递 LIBXML 常量,也不使用 libxml_use_internal_errors 时,我会得到不同的错误,例如:

Note that when I don't pass the LIBXML constants, nor use libxml_use_internal_errors, I get a different error, such as:

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 中无论如何都会抛出错误.

This suggests that the underlying libxml library is indeed supressing the error, but within XMLReader an error is thrown anyway.

推荐答案

看起来除了使用 @ 之外没有办法抑制警告,因为 read() 的 php 源代码 有以下几行:

Looks like there is no way to suppress the warning other than to use @, since php source for read() has following lines:

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);
}

因此,只有 xmlTextReaderRead() 内部的实际解析错误被 libxml_use_internal_errors(true); 或传递给 XMLReader::xml 的选项抑制().

So, only the actual parsing errors inside xmlTextReaderRead() are being suppressed by the libxml_use_internal_errors(true); or the options passed to XMLReader::xml().

这篇关于让 PHP 的 XMLReader 不会在无效文档中抛出 php 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆