php - 我可以在将 html 文件加载到 DOMDocument 时 try catch PHP 警告吗?

标签 php error-handling try-catch warnings domdocument

是否有可能进行某种 try catch 来捕获警告?

例如

if (!$dom->loadHTMLFile($url)) {
    //if cant load file handle error my way
}

对于我正在使用的$url

Warning (2): DOMDocument::loadHTMLFile(MYURL) [domdocument.loadhtmlfile]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden [APP\controllers\import_controller.php, line 62]

Warning (2): DOMDocument::loadHTMLFile() [domdocument.loadhtmlfile]: I/O warning : failed to load external entity "hMYURL" [APP\controllers\import_controller.php, line 62]

我可以用 @ 抑制错误,如果调用返回 false 就做一些事情,但我希望能够捕捉到准确的警告消息然后用它做点什么。

这可能吗?

最佳答案

你应该使用 libxml_use_internal_errors为此。

这个例子改编自手册:

libxml_use_internal_errors(true);
$doc = new DOMDocument();
$res = $doc->loadHTMLFile($url); //this may fail and return FALSE!
foreach (libxml_get_errors() as $error) {
    // handle errors here
}
libxml_clear_errors();

这里不会发出 PHP 通知。

关于php - 我可以在将 html 文件加载到 DOMDocument 时 try catch PHP 警告吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3316899/

相关文章:

WHERE 子句等中的 PHP 未知列

php - 如何在 PHP 脚本中轮换不同的用户

php - 按订单 ID 获取订单总计,无需在 WooCommerce 中进行格式化

javascript - 将Error对象传递给函数会使其消息不确定

c# - 脚本任务失败,没有进入Try&Catch block

php - 从下拉列表中选择值,第二个下拉列表自动更改

node.js - 将数据流式传输到 BigQuery 时没有错误响应

java - 即使从不抛出异常,使用 try-catch block 是否也很昂贵?

ruby - rescue => e 捕获什么类型的异常?

swift - "try"关键字的位置差异