採集某網站時發現 file_get_contents 獲取內容為亂碼,檢查回應 Header 發現 Content-Encoding: gzip。瀏覽器自動解壓,但 PHP 預設不處理壓縮內容。
GZIP 檔案標準規定前 2 位元組為 0x1f 0x8b(十進制 31, 139)。透過讀取前 2 位元組即可快速判斷是否為 GZIP 壓縮內容。
<?php
header('Content-Type: text/html; charset=utf-8');
$url = 'https://www.example.com'; // 目標網站
// 1. 僅讀取前 2 位元組檢測壓縮狀態
$fp = @fopen($url, 'rb');
if (!$fp) {
die("無法開啟遠端資源");
}
$bin = fread($fp, 2);
fclose($fp);
// 2. 解析位元組
$bytes = unpack('C2chars', $bin);
$typeCode = intval($bytes['chars1'] . $bytes['chars2']);
// 3. 判斷是否為 GZIP (31139 = 31 + 139)
$isGzip = ($typeCode === 31139);
// 4. 根據檢測結果決定讀取方式
$finalUrl = $isGzip ? "compress.zlib://{$url}" : $url;
$html = file_get_contents($finalUrl);
// 5. 編碼轉換(若目標頁面為 GBK/Big5)
$html = iconv('gbk', 'utf-8//IGNORE', $html);
echo $html;
?>
| 技術點 | 說明 |
|---|---|
| fopen('rb') | 二進制讀取模式,避免 Windows 環境下換行符轉換干擾 |
| fread($fp, 2) | 僅讀 2 位元組,極低頻寬成本 |
| unpack('C2chars') | 將二進制解包為無號字元(0-255) |
| compress.zlib:// | PHP 串流包裝器,自動解壓 GZIP/DEFLATE |
| iconv //IGNORE | 忽略無法轉換的字元,避免編碼錯誤中斷 |
<?php
function fetch_with_auto_gzip($url, $targetCharset = 'utf-8', $sourceCharset = null) {
// 檢測 GZIP
$fp = @fopen($url, 'rb');
$isGzip = false;
if ($fp) {
$header = fread($fp, 2);
fclose($fp);
$bytes = unpack('C2c', $header);
$isGzip = ($bytes['c1'] === 31 && $bytes['c2'] === 139);
}
// 獲取內容
$content = file_get_contents($isGzip ? "compress.zlib://{$url}" : $url);
if ($content === false) return false;
// 編碼轉換
if ($sourceCharset && $sourceCharset !== $targetCharset) {
$content = iconv($sourceCharset, $targetCharset . '//IGNORE', $content);
}
return $content;
}
// 使用範例
$html = fetch_with_auto_gzip('https://gbk-site.com', 'utf-8', 'gbk');
?>
<?php
function curl_fetch($url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '', // 自動處理 gzip, deflate, br 等
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false, // 僅測試環境使用
]);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
Magic Number 檢測法零依賴、效能極高,適合輕量級採集任務。生產環境建議直接使用 cURL + CURLOPT_ENCODING => '' 讓底層庫自動處理所有壓縮格式,更穩健且支援 Brotli (br) 等新式壓縮。