是否有可能进行某种 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/