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

PHP fopen() vs file_get_contents():適用場景與效能差異

     編輯:PHP 相關知識

兩者皆可讀取本地檔案或遠端 URL,但控制粒度、記憶體模式、串流支援截然不同。

快速對照

特性fopen() + fread()file_get_contents()
回傳型別資源 handle → 需迴圈讀取字串(整檔載入記憶體)
記憶體佔用可逐塊讀取,低記憶體大檔案會撐爆 memory_limit
遠端 HTTP需 allow_url_fopen=On,可控 header/狀態碼同樣需開啟,簡單但無法取得 header
串流控制支援 stream_context、ftell/fseek僅支援 stream_context 參數
二進位安全是(rb 模式)是

本地檔案讀取範例

<?php
// fopen 逐行讀取大檔
$fp = fopen('big.log', 'rb');
if ($fp) {
    while (!feof($fp)) {
        $line = fgets($fp, 4096); // 4KB 緩衝
        // 處理 $line
    }
    fclose($fp);
}

// file_get_contents 適合小檔
$content = file_get_contents('config.json');
$config = json_decode($content, true);
?>

遠端 HTTP 請求範例

<?php
// fopen 可取得回應碼、header
$ctx = stream_context_create(['http' => ['method' => 'GET', 'timeout' => 10]]);
$fp = fopen('https://api.example.com/data', 'rb', false, $ctx);
if ($fp) {
    $meta = stream_get_meta_data($fp);
    $header = $meta['wrapper_data']; // HTTP header 陣列
    $body = stream_get_contents($fp);
    fclose($fp);
}

// file_get_contents 簡單取內文
$body = file_get_contents('https://api.example.com/data', false, $ctx);
// 無法直接拿到 HTTP 狀態碼
?>

選擇建議

  • 大檔案 / 串流處理 / 需要定位 → fopen()
  • 小檔案 / 簡單 API 回應 / 整體 JSON/XML 解析 → file_get_contents()
  • 現代專案:建議改用 Guzzle、Symfony HttpClient 或 cURL,功能更完整、錯誤處理更健全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved