PHP DOMDocument 错误处理

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

问题描述

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

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:

如果传递一个空字符串作为文件名或一个空文件被命名,一个将产生警告.这警告不是由 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 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why can#39;t I update data in an array with foreach loop?(为什么我不能用 foreach 循环更新数组中的数据?)
Foreach for arrays inside of an array(Foreach 用于数组内的数组)
PHP array get next key/value in foreach()(PHP 数组在 foreach() 中获取下一个键/值)
Using preg_match on a multidimensional array to return key values arrays(在多维数组上使用 preg_match 返回键值数组)
php foreach as key, every two number as a group(php foreach 为key,每两个数字为一组)
Treat a PHP class that implements Iterator as an array(将实现 Iterator 的 PHP 类视为数组)