请考虑以下PHP cURL命令:
$url = 'http://bit.ly/faV1vd';
$_h = curl_init();
curl_setopt($_h, CURLOPT_HEADER, 1);
curl_setopt($_h, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($_h, CURLOPT_HTTPGET, 1);
curl_setopt($_h, CURLOPT_URL, $url);
curl_setopt($_h, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
curl_setopt($_h, CURLOPT_DNS_CACHE_TIMEOUT, 2 );
$return = curl_exec($_h);
Run Code Online (Sandbox Code Playgroud)
返回:
HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 29 Apr 2012 12:48:07 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Set-Cookie: _bit=4f9d3887-00215-020af-2f1cf10a;domain=.bit.ly;expires=Fri Oct 26 12:48:07 2012;path=/; HttpOnly
Cache-control: private; max-age=90
Location: http://www.macroaxis.com/invest/market/VZ--Sat-Feb-26-06-16-35-CST-2011?utm_source=twitterfeed&utm_medium=twitter
MIME-Version: 1.0
Content-Length: 209
Run Code Online (Sandbox Code Playgroud)
我想将标题信息拆分为数组,如下所示
[Status] => HTTP/1.1 301 Moved,
[Server] => nginx,
[Date] => Sun, 29 Apr 2012 12:48:07 GMT,
...
[Content-Length] => 209
Run Code Online (Sandbox Code Playgroud)
所以: - 第一行(HTTP/1.1 301 Moved)应为[Status]的值 - 所有其他标题信息应分开 :
我没有成功分割标题信息:
explode("\r\n\r\n", $return);
explode("\r\n", $return);
Run Code Online (Sandbox Code Playgroud)
这不会将标题拆分成一个数组(进一步拆分等:
,如预期的那样.我做错了什么?
小智 7
Altaf Hussain的答案很好但不支持标题响应包含a的情况':'
.即X-URL: http://something.com
.在这种情况下,$myarray
只会包含('X-URL' => 'http')
这可以通过添加limit
参数并将其设置为固定2
.另外,结肠后应该有一个空格.因此,修复bug的完整解决方案是:
$myarray=array();
$data=explode("\n",$return);
$myarray['status']=$data[0];
array_shift($data);
foreach($data as $part){
$middle=explode(": ",$part,2);
$myarray[trim($middle[0])] = trim($middle[1]);
}
print_r($myarray);
Run Code Online (Sandbox Code Playgroud)
使用此选项可将标题拆分为数组
$myarray = array();
$data = explode("\n",$return);
$myarray['status'] = $data[0];
array_shift($data);
foreach($data as $part){
$middle = explode(":",$part);
$myarray[trim($middle[0])] = trim($middle[1]);
}
print_r($myarray);
Run Code Online (Sandbox Code Playgroud)
以及使用 curl_setopt($_h, CURLOPT_NOBODY, 1);
,如果您需要只返回头.
更多信息可以在这里找到
http://altafphp.blogspot.com/2012/04/get-http-headers-of-any-site-using-curl.html