PHP DOMDocument 错误处理

时间:2023-04-09
本文介绍了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 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:通知和警告之间的 PHP 区别 下一篇:什么是标准化的 UTF-8?

相关文章