【问题标题】:Error handling loading a URL错误处理加载 URL
【发布时间】:2013-10-12 17:30:40
【问题描述】:

我正在使用一个名为 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):打开流失败

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

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

【问题讨论】:

  • 警告有什么问题?是有警告还是不能检查加载文件是否有问题?此外(只是提示)PHP 有一个可用的 DomDocument,它比“简单的 HTML DOM”库要好得多。见How to parse and process HTML with PHP?

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


【解决方案1】:

更改以下代码:

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

对于这个:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 正如您正确指出的那样,使用@ 符号会抑制警告,但这不是我要解决的问题。问题是我似乎无法检测到 url 加载何时失败以处理错误。
    • 我刚刚对你的答案投了赞成票(之前的反对票不是我的),现在你的解决方案似乎也是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多