萬盛學電腦網

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

PHP 高效讀取大檔案最佳實踐:逐行、尾部、分塊、記憶體優化

核心原則

**絕對禁止** 對大檔案使用 file_get_contents()、file()、fread($fp, filesize($file)) 等一次性載入整個檔案到記憶體。PHP 記憶體限制 (memory_limit) 通常為 128M-512M,讀取 GB 級日誌會直接 OOM (Out of Memory) 導致進程崩潰。

方法一:逐行讀取 (最常用、記憶體常數級)

<?php
function readLargeFileLineByLine($filepath, callable $callback)
{
    if (!is_readable($filepath)) {
        throw new InvalidArgumentException("檔案不可讀: $filepath");
    }
    
    $handle = fopen($filepath, 'r');
    if (!$handle) {
        throw new RuntimeException("無法開啟檔案: $filepath");
    }
    
    try {
        $lineNumber = 0;
        while (($line = fgets($handle)) !== false) {
            $lineNumber++;
            $callback($line, $lineNumber); // 處理每一行
        }
    } finally {
        fclose($handle);
    }
}

// 使用範例:統計錯誤日誌行數
$errorCount = 0;
readLargeFileLineByLine('/var/log/nginx/error.log', function($line, $num) use (&$errorCount) {
    if (strpos($line, 'ERROR') !== false) {
        $errorCount++;
    }
});
echo "錯誤行數: $errorCount";

方法二:讀取檔案最後 N 行 (tail -n 效果)

<?php
/**
 * 高效讀取檔案最後 N 行 (不讀取整個檔案)
 * 原理:從檔案末尾向前搜尋換行符
 */
function fileTail($filepath, int $lines = 10, int $bufferSize = 4096): array
{
    if (!is_file($filepath) || !is_readable($filepath)) {
        return [];
    }
    
    $handle = fopen($filepath, 'rb');
    $fileSize = fstat($handle)['size'];
    
    if ($fileSize === 0) {
        fclose($handle);
        return [];
    }
    
    $output = [];
    $position = $fileSize;
    $newlineCount = 0;
    $buffer = '';
    
    while ($position > 0 && $newlineCount < $lines) {
        // 計算下一個讀取位置
        $readSize = min($bufferSize, $position);
        $position -= $readSize;
        
        fseek($handle, $position);
        $chunk = fread($handle, $readSize);
        $buffer = $chunk . $buffer;
        
        // 計算完整行數
        $newlineCount = substr_count($buffer, "\n");
    }
    
    fclose($handle);
    
    // 分割並取最後 N 行
    $allLines = explode("\n", rtrim($buffer, "\n"));
    return array_slice($allLines, -$lines);
}

// 使用
$last100 = fileTail('/var/log/access.log', 100);
foreach ($last100 as $line) {
    echo $line . "\n";
}

方法三:固定大小分塊讀取 (二進位/固定記錄)

<?php
function readInChunks($filepath, int $chunkSize = 8192, callable $callback)
{
    $handle = fopen($filepath, 'rb');
    if (!$handle) return;
    
    try {
        while (!feof($handle)) {
            $chunk = fread($handle, $chunkSize);
            if ($chunk === '') break;
            $callback($chunk);
        }
    } finally {
        fclose($handle);
    }
}

// 使用:計算大檔案 MD5 (不載入記憶體)
$hash = hash_init('md5');
readInChunks('large_backup.tar.gz', 8192, function($chunk) use ($hash) {
    hash_update($hash, $chunk);
});
echo "MD5: " . hash_final($hash);

方法四:CSV/TSV 等結構化大檔案處理

<?php
function processLargeCsv($filepath, callable $rowHandler, $delimiter = ',', $enclosure = '"')
{
    $handle = fopen($filepath, 'r');
    if (!$handle) return;
    
    $header = null;
    $rowNum = 0;
    
    try {
        while (($row = fgetcsv($handle, 0, $delimiter, $enclosure)) !== false) {
            $rowNum++;
            if ($header === null) {
                $header = $row; // 第一行作為標題
                continue;
            }
            // 組合關聯陣列
            $record = array_combine($header, $row);
            $rowHandler($record, $rowNum);
        }
    } finally {
        fclose($handle);
    }
}

// 使用:匯入百萬筆會員資料
processLargeCsv('members.csv', function($record, $rowNum) {
    // 批次寫入資料庫 (每 1000 筆 commit 一次)
    static $batch = [];
    $batch[] = $record;
    if (count($batch) >= 1000) {
        insertBatch('members', $batch);
        $batch = [];
    }
});

方法五:SplFileObject 物件導向介面 (PHP 5.1+)

<?php
$file = new SplFileObject('large.log', 'r');
// 可設定旗標
$file->setFlags(
    SplFileObject::READ_AHEAD |   // 預讀
    SplFileObject::SKIP_EMPTY     // 跳過空行
);

foreach ($file as $lineNum => $line) {
    // $line 已自動去除換行符
    if (strpos($line, 'CRITICAL') !== false) {
        echo "Line $lineNum: $line\n";
    }
}

// 直接跳到特定行 (需先 seek)
$file->seek(1000);
echo $file->current(); // 第 1001 行

效能比較與選擇指南

方法記憶體速度適用場景支援 Seek
fgets() 迴圈O(1) 常數快一般文本逐行處理否 (單向)
fseek + fread (tail)O(1)極快 (僅讀尾部)日誌尾部查看、即時監控是
fread 固定分塊O(1)快二進位、哈希、加密、串流傳輸是
fgetcsv()O(1)中CSV/TSV 結構化資料否
SplFileObjectO(1)中物件導向、需隨機存取行號是 (seek)
Generator 封裝O(1)快現代 PHP 風格、可組合管線否

Generator 封裝版 (PHP 5.5+ 推薦風格)

<?php
function readLines(string $filepath): Generator
{
    $handle = fopen($filepath, 'r');
    if (!$handle) return;
    
    try {
        while (($line = fgets($handle)) !== false) {
            yield rtrim($line, "\r\n");
        }
    } finally {
        fclose($handle);
    }
}

// 使用:極其優雅的管線操作
$errors = readLines('/var/log/app.log')
    | array_filter(fn($line) => strpos($line, 'ERROR') !== false)
    | array_map(fn($line) => "[ERROR] $line")
    // 實際需自行實作管線或用迴圈
;

foreach (readLines('/var/log/app.log') as $line) {
    if (strpos($line, 'ERROR') !== false) {
        echo $line . "\n";
    }
}

常見錯誤與避坑指南

錯誤後果正確做法
file_get_contents 大檔案OOM 崩潰改用 fgets/fread 串流
file() 讀取大檔載入全檔到陣列,OOM逐行處理
fopen 後未 fclose檔案句柄洩漏,系統上限try-finally 或 SplFileObject 自動關閉
fgets 未指定長度參數PHP 8.1+ 棄用預設值fgets($fp, 0) 或不傳第二參數 (0 代表無限制)
二進位檔用 'r' 模式Windows 下換行符轉換損壞資料二進位檔必須用 'rb'
忽略編碼問題中文截斷亂碼確認檔案編碼,必要時 mb_convert_encoding

進階:非阻塞/異步讀取 (ReactPHP / Amp)

<?php
// composer require react/filesystem
use React\Filesystem\Filesystem;
use React\EventLoop\Factory;

$loop = Factory::create();
$filesystem = Filesystem::create($loop);

$file = $filesystem->file('large.log');
$stream = $file->createReadStream();

$stream->on('data', function($chunk) {
    // 非阻塞處理 chunk
    processChunk($chunk);
});

$stream->on('end', function() {
    echo "讀取完成\n";
    $loop->stop();
});

$loop->run();

結語

PHP 處理大檔案的核心是**串流處理**。掌握 fopen/fgets/fread/fseek 等底層函數,配合 try-finally 確保資源釋放,即可安全高效處理任意大小檔案。現代 PHP 建議使用 Generator 或 SplFileObject 封裝,提升程式碼可讀性與可組合性。

copyright © 萬盛學電腦網 all rights reserved