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

PHP 取得網頁內容四大方法總結與比較

     編輯:PHP 綜合知識

方法一:file_get_contents (最簡單)

$url = 'https://example.com';
$html = @file_get_contents($url); // 失敗回 false
if ($html === false) { /* 錯誤處理 */ }
// 編碼轉換 (視需要)
$html = mb_convert_encoding($html, 'UTF-8', 'auto');
  • 需 allow_url_fopen=On (php.ini)。
  • 不支援 HTTPS 驗證、Post、Cookie、Header 自訂、超時精確控制。

方法二:cURL (功能最完整)

$ch = curl_init('https://example.com');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => true,  // 生產環境請保持 true
    CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; MyBot/1.0)',
    // 需認證時:
    // CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    // CURLOPT_USERPWD  => 'user:pass',
]);
$html = curl_exec($ch);
$err  = curl_error($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
  • 需安裝 php-curl 擴展 (Windows: 解除註釋 `extension=curl` + 複製 libeay32/ssleay32 至 System32)。
  • 支援所有 HTTP 特性,效能最佳,首選方案。

方法三:fopen + fread + fclose (串流處理)

$fp = @fopen('https://example.com', 'rb');
if (!$fp) die('open failed');
$html = '';
while (!feof($fp)) {
    $html .= fread($fp, 8192);
}
fclose($fp);
  • 同樣需 allow_url_fopen=On。
  • 可邊讀邊處理 (如大檔案、即時解析),記憶體佔用較低。

方法四:GuzzleHttp (現代物件導向 HTTP Client)

// composer require guzzlehttp/guzzle
$client = new GuzzleHttp\Client(['timeout' => 10]);
try {
    $response = $client->get('https://example.com');
    $html = (string)$response->getBody();
    $code = $response->getStatusCode();
} catch (GuzzleHttp\Exception\RequestException $e) {
    // 處理連線錯誤、4xx/5xx (可用 $e->getResponse())
}
  • PSR-7/18 標準、中介軟體、非同步、測試雙工支援完善,現代專案首選。

比較表

維度file_get_contentscURLfopen/freadGuzzle
易用性★★★★★★★★☆☆★★★☆☆★★★★☆
功能完整度★☆☆☆☆★★★★★★★☆☆☆★★★★★
效能/記憶體中 (全載入)高 (可串流)高 (可串流)高 (可串流/非同步)
相依性核心擴展核心Composer 套件
推薦場景簡單 GET、內部測試通用生產環境大檔案/串流現代框架/微服務

編碼處理通用建議

// 1. 從 HTTP Header 取得 charset
$charset = 'UTF-8';
if (preg_match('/charset=([\w-]+)/i', $header, $m)) $charset = strtoupper($m[1]);

// 2. 從 HTML meta 取得 (備援)
if (preg_match('/]+charset=["\']?([\w-]+)/i', $html, $m)) $charset = strtoupper($m[1]);

// 3. 統一轉 UTF-8
$html = mb_convert_encoding($html, 'UTF-8', $charset);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved