PHP 取得遠端網頁原始碼是常見需求,本文介紹從基本 fopen 到現代 cURL 的多種做法,並說明錯誤處理與編碼注意事項。
<?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 支援不穩定。
<?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);
?>
<?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。