<?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);
?>
<?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");
?>
<?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/stream | cURL | file_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。