PHP DOMDocument错误处理 [英] PHP DOMDocument error handling

查看:166
本文介绍了PHP DOMDocument错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我从url加载xml,以便解析它。
但有时这个网址可能无效。在这种情况下,我需要处理错误。
我有以下代码:

In my application I am loading xml from url in order to parse it. But sometimes this url may not be valid. In this case I need to handle errors. I have the following code:

$xdoc = new DOMDocument();
try{
  $xdoc->load($url); // This line causes Warning: DOMDocument::load(...)
                     // [domdocument.load]: failed to open stream: 
                     // HTTP request failed! HTTP/1.1 404 Not Found in ...
} catch (Exception $e) {
  $xdoc = null;
}

if($xdoc == null){
  // Handle
} else {
  // Proceed
}

我知道我可能做错了,但是什么是正确的方式来处理这种异常?我不想在我的页面上看到错误消息。

I know I probably doing it wrong, but what's a correct way to handle this kind of exceptions? I don't want to see error messages on my page.

DOMDocument :: load()手册说:

The manual for DOMDocument::load() says:


如果一个空字符串作为
filename或一个空文件命名,那么将生成
警告。这个
警告不是由libxml生成的,
不能使用libxml的错误
处理函数来处理。

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

但是没有关于如何处理它的信息。

But there is no information on how to handle it.

谢谢。

推荐答案

文档中可以收集到的内容这种方法发出的警告是棘手的,因为它们不是由libxml扩展生成的,因此不能由 libxml_get_last_error()处理。您可以使用错误抑制算子,并检查 false的返回值 ...

From what I can gather from the documentation, handling warnings issued by this method is tricky because they are not generated by the libxml extension and thus cannot be handled by libxml_get_last_error(). You could either use the error suppression operator and check the return value for false...

if (@$xdoc->load($url) === false)
    // ...handle it

...或注册错误处理程序它会引发异常

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

然后抓住它。

这篇关于PHP DOMDocument错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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