HTTP标头,获取特定值

时间:2012-10-24 21:55:21

标签: php curl http-headers

(string) HTTP/1.1 200 OK
Content-Language: en
Content-Type: application/json; charset=utf-8
Date: Wed, 24 Oct 2012 21:38:50 GMT
Server: nginx
Vary: Accept-Language, Cookie, Accept-Encoding
X-Ratelimit-Limit: 5000
X-Ratelimit-Remaining: 4976
transfer-encoding: chunked
Connection: keep-alive

从上面的标题我想要 X-Ratelimit-Remaining 的值。我如何将它存储在php中的变量中。

3 个答案:

答案 0 :(得分:1)

使用get_headers()Documentation)从标头中检索任何值。

答案 1 :(得分:0)

这是使用Curl的替代解决方案:

$ch = curl_init('http://example.com/'); 
curl_setopt_array($ch, array(
    CURLOPT_HEADER => true, 
    CURLOPT_NOBODY => true, 
    CURLOPT_RETURNTRANSFER => true
)); 

$headers = curl_exec($ch);
preg_match('/^X-Ratelimit-Remaining: (.+)$/m', $headers, $m);
list(, $remaining) = $m;

echo '$remaining: ' . $remaining;

答案 2 :(得分:0)

正如 @justderb 已经说过的第一个答案,使用 get_headers() PHP函数。

如果你有一个带有标题信息的字符串。无论如何你都可以转换成数组。

示例:

$url = "http://www.your-web.com";
$xr = get_headers($url, 1);
echo 'The X-Ratelimit-Remaining value is: '.$xr['X-Ratelimit-Remaining'];

或者:

$url = Array(
    "0" => "HTTP/1.1 200 OK",
    "Date" => "Sat, 29 May 2004 12:28:14 GMT",
    "Server" => "Apache/1.3.27 (Unix)  (Red-Hat/Linux)",
    "X-Ratelimit-Remaining" => "4976"
);
echo 'The X-Ratelimit-Remaining value is: '.$url['X-Ratelimit-Remaining'];

希望它有所帮助,

祝你好运!