0

使用 PHP Simple HTML DOM Parser ( http://simplehtmldom.sourceforge.net ),我最近遇到了我经常获取的外部网页没有响应的情况(他们的服务器已关闭)。因此,我自己的网站无法加载(而是在漫长的等待期后显示错误)。

在不成功的获取尝试时向此解析器添加故障保护的最佳方法是什么?

我尝试使用以下内容但没有成功。

include('./inc/simple_html_dom.php');  

$html = file_get_html('http://client0.example.com/dcnum.php?count=1');
$str = $html->find('body',0);
$num = $str->innertext;

if(!$html)
{
 error('No response.')
}

$html->clear(); 
unset($html);

编辑:我还没有时间尝试这个,但也许我可以将我的 'if' 语句直接放在第一行之后(在 $html->find('body',0) 部分之前)。

4

2 回答 2

0

如果我了解您想在他们离线时防止离线...

如果您使用 PHP 的 curl 绑定,您可以使用 curl_getinfo 检查错误代码,如下所示:

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);

/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
    /* Handle 404 here. */
}

curl_close($handle);

/* Handle $response here. */

您还可以检查其他错误代码,如 500、503 等。

于 2013-09-19T12:30:59.080 回答
0

我花了几个小时才弄清楚这一点,令人惊讶的是,关于如何使用 simple_html_dom 处理错误的线索很少。

基本上,您所要做的就是摆脱用于加载内容file_get_html->load_filesimple_html_dom 或任何特定于 simple_html_dom 的方法,而是使用 curl 执行此操作,并将其传递给str_get_html.

我使用了另一个答案的代码,这里是你如何使用它:

function get_with_curl_or_404($url){
    $handle = curl_init($url);
    curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

    $response = curl_exec($handle);

    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

    curl_close($handle);

    if($httpCode == 404 || !$response) { // arbitrary choice to return 404 when anything went wront
        return 404;
    } else {
        return $response;
    }
}

$html = str_get_html(get_with_curl_or_404("http://your-
url.com/index.html"));
if ($html == 404) {
     // Do whatever you want
} else {
     // If not 404, you can use it as usually, ->find(), etc
}

如果它在大型网站上更稳定。

如果这是您正在寻找的那种行为,请尝试一下,并告诉我我没有让您过得愉快。

于 2018-02-10T08:27:18.940 回答