Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

e.g.

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

For the $url I am using I am getting

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]

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.

Is this possible?

like image 322
Lizard Avatar asked Nov 06 '25 19:11

Lizard


1 Answers

You should use libxml_use_internal_errors for this.

This example is adapted from the manual:

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();

No PHP notices will be emitted here.

like image 197
Artefacto Avatar answered Nov 08 '25 12:11

Artefacto