我正在用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,但从未有过。
最佳答案
对于正则表达式而言,这是一项很好的工作,因为状态始终以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
关于php - 解析HTTP状态代码以与API进行交互,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3928812/