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

PHP 讀取網頁內容完整方案:fopen、cURL、stream_context 對比

     編輯:PHP 綜合知識

方法一:fopen + fread(基礎)

<?php
$handle = fopen("https://www.example.com/", "rb");
$contents = "";
while (!feof($handle)) {
    $contents .= fread($handle, 8192);
}
fclose($handle);

// PHP 5+ 簡化版
$handle = fopen("https://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>

方法二:cURL(功能最強、推薦)

<?php
function fetchUrl($url, $timeout = 10) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
        CURLOPT_CONNECTTIMEOUT => $timeout,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_FOLLOWLOCATION => true,      // 支援重導向
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_SSL_VERIFYPEER => false,     // 生產環境建議 true 並配置 CA
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);
    $content = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    if ($errno) throw new Exception("cURL error {$errno}: {$error}");
    return $content;
}

$html = fetchUrl("https://www.baidu.com");
?>

方法三:stream_context(原生、無需擴展)

<?php
$opts = [
    'http' => [
        'method' => 'GET',
        'header' => "Accept-Language: zh-TW\r\n" .
                    "User-Agent: Mozilla/5.0\r\n" .
                    "Cookie: foo=bar\r\n",
        'timeout' => 10,
        'follow_location' => 1,
        'max_redirects' => 5,
    ],
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
    ]
];
$context = stream_context_create($opts);
$fp = fopen('https://www.baidu.com', 'r', false, $context);
$html = stream_get_contents($fp);
fclose($fp);
?>

編碼轉換處理

<?php
// 獲取內容後統一轉 UTF-8
$html = file_get_contents("https://example.com");
// 偵測編碼(需 mbstring)
$encoding = mb_detect_encoding($html, ['UTF-8', 'GB2312', 'BIG-5', 'ISO-8859-1']);
if ($encoding && $encoding !== 'UTF-8') {
    $html = mb_convert_encoding($html, 'UTF-8', $encoding);
}
// 或強制指定來源編碼
$html = iconv('GB2312', 'UTF-8//IGNORE', $html);
?>

方案對比與選型建議

特性fopen/streamcURLfile_get_contents
POST/自定義 Header支援 (stream_context)完美支援需 stream_context
Cookie/Session 維持手動管理內建 Cookie Jar手動管理
HTTPS/SSL 控制有限完整控制有限
多並發/非同步不支援curl_multi 支援不支援
效能中高中
依賴核心 (allow_url_fopen=On)curl 擴展核心 (allow_url_fopen=On)

建議:爬蟲、API 串接、複雜 HTTP 交互首選 cURL;簡單 GET 靜態頁可用 file_get_contents + stream_context;禁用 allow_url_fopen 環境必須用 cURL。

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