首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP file_get_contents 獲取網頁亂碼(GZIP 壓縮)的兩種解決方案

     編輯:PHP 相關知識

使用 file_get_contents 抓取遠端網頁時,若對方伺服器啟用 GZIP 壓縮,直接輸出會出現亂碼。本文提供 cURL 與 stream wrapper 兩種解法。

原因

回應標頭含 Content-Encoding: gzip,內容為壓縮後的二進位資料,瀏覽器會自動解壓,但 file_get_contents 不會自動處理。

方案一:使用 cURL(推薦,功能完整)

function curl_get($url, $gzip = false) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    if ($gzip) {
        curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // 關鍵:自動解壓 gzip/deflate
    }
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}
// 使用
$html = curl_get('https://example.com', true);

方案二:file_get_contents 搭配 zlib stream wrapper

$html = file_get_contents("compress.zlib://" . $url);

無論目標頁面是否壓縮,此寫法均能正常工作(PHP 內建 zlib 擴充需啟用)。

cURL 安裝提醒

  • Windows:php.ini 啟用 extension=php_curl.dll。
  • Linux:yum install php-curl 或 apt-get install php-curl,重啟 PHP-FPM/Apache。

總結

簡單專案用 compress.zlib:// 最輕量;需處理 Cookie、Header、POST、HTTPS 驗證等複雜場景請改用 cURL。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved