【问题标题】:file_get_html cant open streamfile_get_html 无法打开流
【发布时间】:2018-07-21 19:21:22
【问题描述】:

我正在使用 html_dom 抓取网站。

$url = $_POST["textfield"];
$html = file_get_html($url);

html_dom.php

function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
    // We DO force the tags to be terminated.
    $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
    // For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done.
    $contents = file_get_contents($url, $use_include_path, $context);
    // Paperg - use our own mechanism for getting the contents as we want to control the timeout.
    //$contents = retrieve_url_contents($url);
    if (empty($contents) || strlen($contents) > MAX_FILE_SIZE)
    {
        return false;
    }
    // The second parameter can force the selectors to all be lowercase.
    $dom->load($contents, $lowercase, $stripRN);
    return $dom;
}

问题是,如果互联网连接太慢,它仍然会继续使用 file_get_html,那么它将是一个警告错误,提示无法打开流和致命错误:最大执行时间 30 秒。如果检测到警告错误,我尝试通过停止该功能来解决它​​:

function errHandle($errNo, $errStr, $errFile, $errLine) {
    $msg = "Slow Internet Connection";
    if ($errNo == E_NOTICE || $errNo == E_WARNING) {
        throw new ErrorException($msg, $errNo);
    } else {
        echo $msg;
    }
}

set_error_handler('errHandle');

但它仍然在执行时打印致命错误。关于如何解决这个问题的任何想法?

【问题讨论】:

  • 你的标题有点误导;您真正需要的是在 GET 超时时如何处理错误情况。我没有做足够的 PHP 来知道如何在没有大量研究的情况下处理这个问题,但在 C# 中,我们只需将外部调用包装在 try..catch 块中。快速 Bing 搜索找到了这个例子:stackoverflow.com/a/17549618/73680
  • 试试 curl 或 guzzle。

标签: php html simple-html-dom


【解决方案1】:

如果时间过长可以增加时间限制:

http://php.net/manual/en/function.set-time-limit.php

您无法在 php 5.6 或更低版本中捕获致命错误。在 php 7+ 中,您可以使用

try {
   doSomething();
} catch (\Throwable $exception) {
   // error handling
   echo $exception->getMessage();
}

不确定你是否能赶上执行时间限制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-01
    • 2014-07-26
    • 2019-03-29
    • 2015-05-05
    • 2017-03-28
    • 2019-12-03
    • 2014-11-26
    • 2015-10-03
    相关资源
    最近更新 更多