将html文件加载到DOMDocument时可以尝试捕获PHP警告吗? [英] Can I Try-Catch PHP Warnings while loading an html file into DOMDocument?
问题描述
是否可以进行某种尝试捕获以捕获警告?
Is it possible to do some sort of try catch that will catch warnings?
例如
if (!$dom->loadHTMLFile($url)) {
//if cant load file handle error my way
}
对于我正在使用的 $ url
警告(2):DOMDocument :: loadHTMLFile(MYURL)[domdocument.loadhtmlfile]:无法打开流:HTTP请求失败! HTTP / 1.0 403禁止
[APP\controllers\import_controller.php,第62行]
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]
警告(2):DOMDocument :: loadHTMLFile()[ domdocument.loadhtmlfile]:I / O警告:无法加载外部实体 hMYURL [APP\controllers\import_controller.php,第62行]
Warning (2): DOMDocument::loadHTMLFile() [domdocument.loadhtmlfile]: I/O warning : failed to load external entity "hMYURL" [APP\controllers\import_controller.php, line 62]
我可以使用 @
抑制错误,如果调用返回 false
,但我希望能够捕获确切的警告消息,然后对其进行处理。
I could just suppress the error with @
, and do something if the call returns false
, but I want to be able to catch the exact warning message and then do something with it.
这可能吗?
推荐答案
您应使用 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通知。
No PHP notices will be emitted here.
这篇关于将html文件加载到DOMDocument时可以尝试捕获PHP警告吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!