解析用于与API交互的HTTP状态代码

时间:2010-10-13 23:14:08

标签: php curl http-status-codes

我正在PHP中构建一个脚本来与API交互,并且需要能够解析API给我的HTTP状态代码。在大多数情况下,它给出了以下回答之一:

HTTP/1.1 401 Unauthorized
HTTP/1.1 403 Forbidden 
HTTP/1.1 404 Not Found 
HTTP/1.1 410 Gone 

我需要能够识别正在给出哪个响应,并且,如果它的401或410,继续,但是,如果它是401或403,则跟踪并在几个之后关闭脚本行(因为我超过了当天的通话限制)。

我的代码非常简单:

for($i = $start;$i < $end;$i++)
{
     // construct the API url
     $url = $base_url.$i.$end_url;
     // make sure that the file is accessible
     if($info = json_decode(file_get_contents($url)))
     {
        // process retrieved data
     } else {
        // what do I put here?
     }
}

我的问题是我不知道在'else'循环中放什么。我正在使用CodeIgniter框架,如果有人知道任何使用的快捷方式。此外,我愿意使用cURL,但从未有过。

2 个答案:

答案 0 :(得分:5)

这对于正则表达式来说是一个很好的工作,因为状态始终采用version code text的形式:

$matches = array();
preg_match('#HTTP/\d+\.\d+ (\d+)#', $http_response_header[0], $matches);
echo $matches[1]; // HTTP/1.1 410 Gone return 410

preg_match

$http_response_header

答案 1 :(得分:2)