直接 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 - 第 = $page ?> / = $totalPages ?> 頁</h2>
<div>= $display ?></div>
<nav>
1): ?>
<a href="?page=1">首頁</a> |
<a href="?page== $page-1 ?>">上一頁</a> |
<a href="?page== $page+1 ?>">下一頁</a> |
<a href="?page== $totalPages ?>">末頁</a>
</nav>
</body>
</html>
\n 轉 <br> 保留排版;實務上建議改用 nl2br() 或正則統一處理。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;
}