【发布时间】:2016-03-03 02:17:53
【问题描述】:
我的代码最初适用于大多数网站,除了 (Facebook.com) 之类的网站。所以我插入了curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);,它开始在所有网站上运行,甚至得到了我需要的正确结果。
我的问题是我在这条线上收到Notice: Undefined offset: 1:
list($k,$v)=explode(':',$header);
即使我得到了正确的结果。
我注意到只有当我有CURLOPT_FOLLOWLOCATION 行时我才得到那个notice,但没有那行,我无法获得一些网站 gzip 压缩信息
我的代码:
$ch = curl_init("http://facebook.com/");
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$buffer = curl_exec($ch);
$curl_info = curl_getinfo($ch);
curl_close($ch);
$header_size = $curl_info["header_size"];
$headers = substr($buffer, 0, $header_size);
$body = substr($buffer, $header_size);
function getEncoding(&$headers){
$arr=explode("\r\n",trim($headers));
array_shift($arr);
foreach($arr as $header){
list($k,$v)=explode(':',$header);
if ('content-encoding'==strtolower($k)){
return trim($v);
}
}
return false;
}
$encoding=getEncoding($headers);
if ($encoding) {
echo "Using: ".$encoding;
}else{
echo "None";
}
【问题讨论】:
-
该错误意味着
$header中没有:。发生这种情况时尝试回显$header。 -
$header中有多个:。由于它很长,无法在此处粘贴整个输出@Barmar -
@barmar stackoverflow.com/questions/9183178/… 这是我收到的信息
-
错误不会无缘无故发生。只有当
$header中没有:时,才会发生该错误。将if(!strstr($header, ':')) { echo "Bad header: $header"; }放入循环中。
标签: php curl error-handling gzip