使用CURL检测错误 [英] Detecting errors with CURL

查看:79
本文介绍了使用CURL检测错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP中的cURL解析网站列表,但是遇到了检测返回响应时遇到的任何html错误的问题。根据php手册,以下代码段应有助于在调用过程中检测到任何错误(错误意味着该页面对于解析无用,因此类似404或500的错误在我的书中):

I am trying to parse a list of websites using cURL in PHP but am running into the issue of detecting any html errors encountered when getting back a response. According to the php manual, the below code snippet should help detect any errors (error means the page is useless for parsing so anything like a 404 or 500 is an error in my book) during the call:

if(curl_error($c)) {
    print_r( 'error:' . curl_error($curl));
}

以上代码确实可处理404错误,但无法捕获500个错误示例(可能会捕获更多错误)。我当然可以使用:

The above code does work for 404 errors but is unable to catch 500 errors for example (there may be more errors it doesnt catch). I can of course use this:

$httpCode = curl_getinfo ( $curl, CURLINFO_HTTP_CODE );

但是后来我不得不手动添加检查以评估变量,如果结果是500或404或401等。我如何简单而准确地忽略对解析网站无用的响应?

But then i would have to manually add checks to evaluate the variable and ignore the result if the result was a 500 or 404 or 401 etc. How can i simply and accurately ignore the responses which are not useful for parsing the website?

推荐答案

$wrong_http_codes = '^0|4.*|5.*$';
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (preg_match("/$wrong_http_codes/", $http_code) === 1) {
    echo 'Error';
}

这篇关于使用CURL检测错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆