curl 和 file_get_contents 抓取網頁亂碼的解決之道 filegetcontents逾時 js file get contents wp file get contents

來源:互聯網
上載者:User
今天用 curl_init 函數抓取搜狐的網頁時,發現採集的網頁時亂碼,經過分析發現原來是伺服器開啟了gzip壓縮功能。只要往函數 curl_setopt 添加多個選項 CURLOPT_ENCODING 解析 gzip 就可以正確解碼了。
還有如果抓取的網頁時 GBK 編碼,但是指令碼確是 utf-8 編碼,還得把抓取的網頁再用函數 mb_convert_encoding 轉換下。
$tmp = sys_get_temp_dir();
$cookieDump = tempnam($tmp, 'cookies');
$url = 'http://tv.sohu.com';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 1);// 顯示返回的Header地區內容
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉
curl_setopt ($ch, CURLOPT_TIMEOUT, 10);// 設定逾時限制
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // 擷取的資訊以檔案流的形式返回
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);// 連結逾時限制
curl_setopt ($ch, CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));//設定 http 頭資訊
curl_setopt ($ch, CURLOPT_ENCODING, 'gzip,deflate');//添加 gzip 解碼的選項,即使網頁沒啟用 gzip 也沒關係
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookieDump); // 存放Cookie資訊的檔案名稱
$content = curl_exec($ch);
// 把抓取的網頁由 GBK 轉換成 UTF-8
$content = mb_convert_encoding($content,"UTF-8","GBK");
?>
$url = 'http://tv.sohu.com';
// 只要添加 compress.zlib 選項,即使伺服器啟用了gzip 壓縮功能,就能夠解碼了
$content = file_get_contents("compress.zlib://".$url);
// 把抓取的網頁由 GBK 轉換成 UTF-8
$content = mb_convert_encoding($content,"UTF-8","GBK");
?>
原文:http://woqilin.blogspot.com/2014/05/curl-filegetcontents.html

以上就介紹了curl 和 file_get_contents 抓取網頁亂碼的解決之道,包括了file_get_contents方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.