【发布时间】:2013-02-02 08:49:49
【问题描述】:
我正在编写解析器,并尝试对异常进行良好的错误处理。
以下示例代码:
<?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 中还是会抛出错误。
【问题讨论】:
-
也许实现
try和catch来跟踪错误? -
它们不是例外,它们是传统的 PHP 错误。我可以使用 try..catch 的唯一方法是使用
set_error_handler,我想在编写库时避免这种情况,并且我不想更改全局状态。
标签: php xml xml-parsing xmlreader