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

PHP 取得網頁原始碼:fopen/fgets 串流讀取實作

     編輯:PHP 相關知識

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;
?>

進階:支援 HTTPS、Header 自訂、逾時控制

<?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');
?>

stream_context 關鍵選項

限制與替代方案

  • allow_url_fopen 在共享主機常被關閉,生產環境強烈建議使用 cURL(功能完整、效能更好、錯誤處理更豐富)。
  • 不支援並發請求、Keep-Alive、進度回調等進階功能。
  • 大檔案下載記憶體壓力大,需搭配 fread 迴圈分塊處理。

理解串流上下文機制,有助於在受限環境下快速實作 HTTP 客戶端。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
選項說明
methodGET/POST/PUT/DELETE
header自訂 Header 字串(換行分隔)
contentPOST/PUT 請求主體
timeout秒數,浮點數支援毫秒
follow_location1=自動追蹤 Location
ignore_errorstrue=非 2xx 也回傳內容
proxytcp://proxy:port