0

I'm using a library called Simple HTML DOM

One of it's methods, loads the url into a DOM object:

function load_file()
{
    $args = func_get_args();
    $this->load(call_user_func_array('file_get_contents', $args), true);
    // Throw an error if we can't properly load the dom.
    if (($error=error_get_last())!==null) {
        $this->clear();
        return false;
    }
}

In order to test error handling, I created this code:

include_once 'simple_html_dom.php';
function getSimpleHtmlDomLoaded($url)
{
  $html = false;
  $count = 0;
  while ($html === false && ($count < 10)) {
    $html = new simple_html_dom();
    $html->load_file($url);
    if ($html === false) {
      echo "Error loading url!\n";
      sleep(5);
      $count++;
    }
  }
  return $html;
}

$url = "inexistent.html";
getSimpleHtmlDomLoaded($url);

The idea behind this code it's to try again if the url is failing to load, if after 10 attemps still fails, it should return false.

However it seems that with an inexistent url, the load_file method never returns false.

Instead I get the following warning message:

PHP Warning: file_get_contents(inexisten.html): failed to open stream

Any idea how to fix this?

Note: Preferably I would like to avoid hacking into the library.

hakre
  • 193,403
  • 52
  • 435
  • 836
rfc1484
  • 9,441
  • 16
  • 72
  • 123
  • What is your problem with the warning? That there is a warning or that you can not check whether there was a problem loading the document? Also (just a tip) PHP has a DomDocument available that is far superior than the "simple HTML DOM" library. See [How to parse and process HTML with PHP?](http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) – hakre Sep 24 '12 at 11:42

2 Answers2

2

Change your following code:

$html->load_file($url);
if ($html === false) {

for this one:

$ret = $html->load_file($url);
if ($ret === false) {

because you were checking object instance instead of the returned value from load_file() method.

Nelson
  • 49,283
  • 8
  • 68
  • 81
0

By adding the @ sign before a method call, any warnings get supressed. If you use this, always be sure to check for errors yourself as you do now and are sure no other methods are available to make sure no warnings and/or errors pop up.

You should check the actual data that is saved somewhere by the load() method if that equals FALSE instead of the object instance $html.

zeebonk
  • 4,864
  • 4
  • 21
  • 31
  • As you correctly pointed out, using the @ sign the warning would get supressed, however that's not the problem I want to fix. The problem is the fact that I can't seem to detect when the url loading is failing in order to handle the error. – rfc1484 Sep 24 '12 at 11:29
  • I've just upvoted your answer (the previous downvote was not mine), your solution now it seems also correct. – rfc1484 Sep 24 '12 at 11:49