加载URL时出错

时间:2012-09-24 11:20:45

标签: php error-handling simple-html-dom

我正在使用名为Simple HTML DOM的库

其中一个方法,将url加载到DOM对象中:

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;
    }
}

为了测试错误处理,我创建了这段代码:

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

这个代码背后的想法是如果url无法加载再次尝试,如果10次尝试仍然失败,它应该返回false。

然而,似乎使用不存在的url,load_file方法永远不会返回false。

相反,我收到以下警告信息:

  

PHP警告:file_get_contents(inexisten.html):无法打开流

知道如何解决这个问题吗?

注意:我最好避免入侵图书馆。

2 个答案:

答案 0 :(得分:2)

更改以下代码:

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

这个:

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

因为您正在检查对象实例而不是load_file()方法返回的值。

答案 1 :(得分:0)

通过在方法调用之前添加@符号,可以抑制任何警告。如果您使用此功能,请务必自行检查错误,并确保没有其他方法可用,以确保不会弹出警告和/或错误。

如果等于FALSE而不是对象实例$ html,则应检查load()方法保存的实际数据。