萬盛學電腦網

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

PHP 讀取大型文字檔並分頁顯示:記憶體優化實作

直接 file() 讀取大型文字檔會耗盡記憶體。本文示範用 file_get_contents() 讀入字串,配合自訂 msubstr() 按位元組安全截取(支援中文換行),實作分頁顯示。

核心程式碼

<?php
session_start();
$page = empty($_GET['page']) ? 1 : max(1, intval($_GET['page']));
$pageSize = 5000; // 每頁位元組數

// 讀取整個檔案到字串(適合較大但仍能裝入記憶體的檔案)
$content = file_get_contents("example.txt");
$totalBytes = strlen($content);
$totalPages = ceil($totalBytes / $pageSize);

// 安全截取函數:處理中文雙位元組不斷字
function msubstr($str, $start, $len) {
    $result = '';
    $end = min($start + $len, strlen($str));
    for ($i = $start; $i < $end; $i++) {
        $char = $str[$i];
        // 簡易處理:遇到換行符轉 
if (ord($char) === 0x0A) { // \n $result .= '<br />'; } else { $result .= $char; } } return $result; } // 計算當頁起始位元組 $start = ($page - 1) * $pageSize; $display = msubstr($content, $start, $pageSize); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文字檔分頁閱讀</title> <style>body{font-family:monospace;line-height:1.6;max-width:800px;margin:2rem auto;padding:0 1rem;}</style> </head> <body> <h2>example.txt - 第 / 頁</h2> <div></div> <nav> 1): ?> <a href="?page=1">首頁</a> | <a href="?page=">上一頁</a> | <a href="?page=">下一頁</a> | <a href="?page=">末頁</a> </nav> </body> </html>

關鍵點解析

  • 位元組分頁而非行分頁:避免逐行讀取開銷,適合純文字閱覽(如小說、日誌)。
  • msubstr() 處理換行:將 \n 轉 <br> 保留排版;實務上建議改用 nl2br() 或正則統一處理。
  • 中文斷字風險:按位元組截取可能切斷多位元組字元(UTF-8 中文 3 bytes),顯示亂碼。改進:用 mb_substr() 按字元截取,或預先 mb_convert_encoding() 到單位元組編碼。
  • 超大檔案(>記憶體):必須用 fopen() + fseek() + fread() 分塊讀取,見 ID 66592。

改進版:按行分頁(更適合結構化日誌)

// 只讀取所需行數,避免載入整個檔案
function readLines($file, $page, $pageSize) {
    $handle = fopen($file, 'r');
    $skip = ($page - 1) * $pageSize;
    for ($i = 0; $i < $skip && !feof($handle); $i++) fgets($handle);
    $lines = [];
    for ($i = 0; $i < $pageSize && !feof($handle); $i++) {
        $lines[] = rtrim(fgets($handle));
    }
    fclose($handle);
    return $lines;
}
copyright © 萬盛學電腦網 all rights reserved