方法一:
header("content-type:text/html;charset=utf-8");
$url="http://115.47.116.10/rest/keyword
'";
$content = file_get_contents("compress.zlib://".$url);
$arr=json_decode($content,true);
print_r($arr);
二:
curl亂碼有兩個方面的原因一個是因為我們采集頁面的php頁面編碼與遠程文檔編碼不致導致的,另一種可能是頁面進入了gzip壓縮傳輸導致的,那么我們要如何解決這些問題呢?
gzip壓縮傳輸導致亂碼
今天在采集京東的時候發現返回的數據是亂碼,網上說可能和壓縮有關,看了一下京東的頭信息的確進行gzip加密,好吧,那就解壓吧
1
|
$return = gzdecode($return); //將return的字符進行解碼
|
另一種解決辦法
1
|
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
|
頁面編碼問題
1
|
mb_convert_encoding($str, 'utf-8', 'GBK,UTF-8,ASCII');
|
完整代碼示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// curl 偽造agent抓取頁面
function http_get($URL,$key='baidu') {
$agent = Flight::get('flight.spider_agent')[$key];
if( !$agent ){
return false;
}
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_USERAGENT, $agent);
curl_setopt($c, CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));
curl_setopt($c, CURLOPT_ENCODING, 'gzip,deflate');//這個是解釋gzip內容.................
curl_setopt($c, CURLOPT_URL, $URL);
curl_setopt($c, CURLOPT_TIMEOUT,2);
$contents = curl_exec($c);
$contents = mb_convert_encoding($contents, 'utf-8', 'GBK,UTF-8,ASCII');
$httpCode = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
return ['data'=>$contents,'http_code'=>$httpCode];
}
|