萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP fopen() vs file_get_contents():檔案與網路讀取完整對比指南

快速對比表

特性fopen() + fread()file_get_contents()
回傳值資源控制代碼 (handle)字串 (完整內容)
記憶體模式流式 (逐塊讀取)一次性載入全部
大檔案支援✅ 極佳❌ 受 memory_limit 限制
HTTP 串流支援 (需啟用 allow_url_fopen)支援 (需啟用 allow_url_fopen)
HTTP 選項控制stream_context_create() 完整控制stream_context_create() 支援
錯誤處理回傳 false,需檢查回傳 false,需檢查
關閉責任手動 fclose()自動關閉
二進位安全✅ (rb 模式)✅
寫入支援✅ (fwrite)❌ (需 file_put_contents)

fopen() 完整操作流程

本地檔案讀取

<?php
$file = 'data.log';
$handle = fopen($file, 'rb'); // 二進位唯讀
if (!$handle) {
    die("無法開啟檔案: $file");
}

$chunkSize = 8192; // 8KB 緩衝
while (!feof($handle)) {
    $chunk = fread($handle, $chunkSize);
    if ($chunk === false) break;
    // 處理 chunk (輸出、解析、寫入其他檔案...)
    echo $chunk;
}

fclose($handle); // 必須關閉釋放資源

逐行讀取 (大型日誌/CSV)

<?php
$handle = fopen('huge.csv', 'r');
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // fgets 保留換行符,需 trim
        $data = str_getcsv(trim($line));
        // 處理 $data...
    }
    fclose($handle);
}

HTTP 請求 (底層控制)

<?php
$url = 'https://api.example.com/data';
$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => "User-Agent: MyApp/1.0\r\nAccept: application/json\r\nAuthorization: Bearer $token",
        'timeout' => 10,
        'ignore_errors' => true, // 取得 4xx/5xx 回應內容
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
    ]
]);

$handle = fopen($url, 'rb', false, $context);
if (!$handle) {
    die('HTTP request failed');
}

$response = '';
while (!feof($handle)) {
    $response .= fread($handle, 8192);
}
fclose($handle);

// 取得 HTTP 狀態碼 (從 $http_response_header 全域變數)
$statusLine = $http_response_header[0] ?? '';
preg_match('/\d{3}/', $statusLine, $matches);
$httpCode = (int)($matches[0] ?? 0);

echo "HTTP $httpCode\n";
echo $response;

file_get_contents() 簡潔用法

本地檔案一次讀取

<?php
$content = @file_get_contents('config.json');
if ($content === false) die('Read failed');
$config = json_decode($content, true);

HTTP GET 請求

<?php
$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => "User-Agent: MyApp\r\nAccept: application/json",
        'timeout' => 5,
    ]
]);
$json = @file_get_contents('https://api.example.com/users', false, $context);
if ($json === false) {
    // 錯誤處理
} else {
    $data = json_decode($json, true);
}

HTTP POST 請求

<?php
$postData = http_build_query(['name' => 'John', 'age' => 30]);
$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($postData),
        'content' => $postData,
        'timeout' => 10,
    ]
]);
$result = @file_get_contents('https://api.example.com/users', false, $context);

效能與記憶體實測

<?php
// 建立 100MB 測試檔
$testFile = '/tmp/test_100mb.dat';
if (!file_exists($testFile)) {
    $h = fopen($testFile, 'wb');
    for ($i = 0; $i < 100; $i++) fwrite($h, str_repeat('x', 1024 * 1024));
    fclose($h);
}

ini_set('memory_limit', '64M');

// file_get_contents: 會嘗試載入 100MB → 可能 OOM
$start = microtime(true);
$content = @file_get_contents($testFile);
echo "file_get_contents: " . ($content ? 'OK' : 'FAIL') . ", " . (microtime(true)-$start) . "s, Mem: " . memory_get_peak_usage(true) . "\n";

// fopen 流式: 記憶體恆定
$start = microtime(true);
$handle = fopen($testFile, 'rb');
$total = 0;
while (!feof($handle)) {
    $chunk = fread($handle, 8192);
    $total += strlen($chunk);
}
fclose($handle);
echo "fopen stream: OK, " . (microtime(true)-$start) . "s, Mem: " . memory_get_peak_usage(true) . "\n";

/* 典型輸出 (64M limit):
file_get_contents: FAIL, 0.02s, Mem: 67MB (OOM)
fopen stream: OK, 0.15s, Mem: 2MB
*/

進階:自訂串流封裝協定

<?php
// 註冊自訂協定:memory://, temp://, php://filter, phar://, zip://, ssh2://, s3:// (擴展)
$content = file_get_contents('php://filter/read=string.toupper/resource=data.txt');
echo $content; // 大寫輸出

// 壓縮檔直接讀取
$content = file_get_contents('compress.zlib://data.gz');
// ZIP 內檔案
$content = file_get_contents('zip://archive.zip#inner.txt');

選擇決策樹

需要讀取資料
├─ 大檔案 (>10MB) / 未知大小 / 串流處理 / 需精確控制 HTTP → fopen()
├─ 小檔案 (<10MB) / 完整內容需一次處理 / 程式碼簡潔優先 → file_get_contents()
├─ 需寫入/追加/修改檔案 → fopen() (r+/w/a 模式)
├─ 複雜 HTTP (Cookie、重導向、憑證、多部分表單) → cURL (更強大)
└─ 現代專案建議 → HTTP Client 庫 (Guzzle, Symfony HttpClient, Laravel HTTP)

現代最佳實踐:PSR-18 HTTP Client

<?php
// composer require guzzlehttp/guzzle php-http/guzzle7-adapter nyholm/psr7
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;

class ApiClient {
    public function __construct(
        private ClientInterface $client,
        private RequestFactoryInterface $requestFactory
    ) {}

    public function get(string $url, array $headers = []): array {
        $request = $this->requestFactory->createRequest('GET', $url);
        foreach ($headers as $k => $v) {
            $request = $request->withHeader($k, $v);
        }
        $response = $this->client->sendRequest($request);
        return json_decode($response->getBody()->getContents(), true);
    }
}

理解 `fopen()` 流式處理與 `file_get_contents()` 一次性讀取的本質差異,能根據場景選擇最適當的工具,避免記憶體溢出與效能瓶頸。

copyright © 萬盛學電腦網 all rights reserved