PHP 允許直接使用 fopen() 開啟 HTTP/HTTPS URL(需 allow_url_fopen=On),搭配 fgets() 逐行讀取,即可獲取遠端網頁原始碼,無需 cURL 擴展。
<?php
$url = 'https://www.example.com';
$handle = @fopen($url, 'r');
if (!$handle) {
die("無法開啟 $url");
}
$content = '';
while (($line = fgets($handle, 1024)) !== false) {
$content .= $line;
}
fclose($handle);
echo $content;
?>
<?php
function fetchUrl(string $url, array $options = []): ?string {
$context = stream_context_create([
'http' => [
'method' => $options['method'] ?? 'GET',
'header' => $options['header'] ?? "User-Agent: PHP Stream Client\r\nAccept: */*\r\n",
'timeout' => $options['timeout'] ?? 10,
'follow_location' => $options['follow_location'] ?? 1,
'max_redirects' => $options['max_redirects'] ?? 5,
'ignore_errors' => true, // 取得 4xx/5xx 內容
],
'ssl' => [
'verify_peer' => $options['verify_peer'] ?? true,
'verify_peer_name' => $options['verify_peer_name'] ?? true,
]
]);
$content = @file_get_contents($url, false, $context);
if ($content === false) {
error_log("fetchUrl 失敗: $url");
return null;
}
return $content;
}
// 使用
$html = fetchUrl('https://api.github.com/users/octocat');
?>
| 選項 | 說明 |
|---|---|
| method | GET/POST/PUT/DELETE |
| header | 自訂 Header 字串(換行分隔) |
| content | POST/PUT 請求主體 |
| timeout | 秒數,浮點數支援毫秒 |
| follow_location | 1=自動追蹤 Location |
| ignore_errors | true=非 2xx 也回傳內容 |
| proxy | tcp://proxy:port |