萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 讀取網頁原始碼的多種方法

前言

PHP 取得遠端網頁原始碼是常見需求,本文介紹從基本 fopen 到現代 cURL 的多種做法,並說明錯誤處理與編碼注意事項。

方法一:fopen + fgets(舊式,不建議生產環境)

<?php
$url = 'https://www.example.com';
$fp = @fopen($url, 'r');
if (!$fp) {
    die("無法開啟 $url");
}

$contents = '';
while ($line = fgets($fp, 1024)) {
    $contents .= $line;
}
fclose($fp);

echo htmlspecialchars($contents);
?>

缺點:無法設定 timeout、User-Agent、處理重導向、HTTPS 支援不穩定。

方法二:file_get_contents(簡單但功能有限)

<?php
$url = 'https://www.example.com';
$context = stream_context_create([
    'http' => [
        'timeout' => 10,
        'user_agent' => 'Mozilla/5.0 (compatible; PHP Bot)'
    ]
]);
$contents = @file_get_contents($url, false, $context);
if ($contents === false) {
    die('讀取失敗');
}
echo htmlspecialchars($contents);
?>

方法三:cURL(推薦,功能最完整)

<?php
function fetch_url($url, $options = []) {
    $ch = curl_init($url);
    $defaults = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
        CURLOPT_SSL_VERIFYPEER => true, // 生產環境建議開啟
    ];
    curl_setopt_array($ch, $defaults + $options);
    $content = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    if ($errno) {
        throw new RuntimeException("cURL 錯誤 ($errno): $error");
    }
    if ($info['http_code'] >= 400) {
        throw new RuntimeException("HTTP 錯誤: {$info['http_code']}");
    }
    return $content;
}

try {
    $html = fetch_url('https://www.example.com');
    echo htmlspecialchars($html);
} catch (Exception $e) {
    echo '錯誤: ' . $e->getMessage();
}
?>

編碼處理提醒

取得內容後,若網頁非 UTF-8,需轉碼:

$encoding = mb_detect_encoding($contents, ['UTF-8', 'BIG5', 'GB2312']);
if ($encoding && $encoding !== 'UTF-8') {
    $contents = mb_convert_encoding($contents, 'UTF-8', $encoding);
}

總結

生產環境請使用 cURL,功能完整且可控性最高;簡單腳本可用 file_get_contents 搭配 stream context。

copyright © 萬盛學電腦網 all rights reserved