fopen() vs file_get_contents():適用場景與效能差異兩者皆可讀取本地檔案或遠端 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);
?>
<?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()file_get_contents()Guzzle、Symfony HttpClient 或 cURL,功能更完整、錯誤處理更健全。