file(string $filename, int $flags = 0, ?resource $context = null): array|false 將整個檔案讀入陣列,每行為一個元素,保留換行符。適合小型檔案,大檔案會耗盡記憶體。
<?php
$lines = file('/tmp/file.txt');
if ($lines === false) {
die('讀取失敗');
}
foreach ($lines as $lineNum => $line) {
// 移除尾部換行符(file() 保留 \n 或 \r\n)
$clean = rtrim($line, "\r\n");
echo "Line {$lineNum}: {$clean}\n";
}
?>
| Flag | 效果 |
|---|---|
| 自動移除每行尾部換行符(推薦) | |
| 跳過空白行 | |
| 以文字模式讀取(Windows 影響換行轉換) |
<?php
// 一次搞定:去換行符 + 跳過空行
$lines = file('/tmp/file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
// $line 已經是乾淨的字串
processLine($line);
}
?>
<?php
// ⚠️ 危險:100MB 檔案會佔用 100MB+ 記憶體
$lines = file('/var/log/huge.log'); // 可能觸發 memory_limit
// ✅ 正確:逐行處理,記憶體 O(1)
$handle = fopen('/var/log/huge.log', 'r');
while (($line = fgets($handle)) !== false) {
processLine(rtrim($line, "\r\n"));
}
fclose($handle);
?>
<?php
/**
* 逐行讀取大檔案,支援回呼處理
* @param string $path
* @param callable $callback function(string $line, int $lineNum): bool|void 回傳 false 中斷
* @param int $bufferSize 緩衝區大小
*/
function readLargeFile(string $path, callable $callback, int $bufferSize = 8192): void {
$handle = fopen($path, 'r');
if (!$handle) throw new RuntimeException("無法開啟: {$path}");
$lineNum = 0;
try {
while (($line = fgets($handle, $bufferSize)) !== false) {
$line = rtrim($line, "\r\n");
if ($callback($line, ++$lineNum) === false) {
break; // 允許提前終止
}
}
} finally {
fclose($handle);
}
}
// 使用範例:只找前 10 個錯誤行
$errors = [];
readLargeFile('/var/log/app.log', function($line, $num) use (&$errors) {
if (str_contains($line, 'ERROR')) {
$errors[] = "Line {$num}: {$line}";
if (count($errors) >= 10) return false; // 找夠就停
}
});
print_r($errors);
?>
<?php
// 使用 SplFileObject 內建 CSV 解析
$csv = new SplFileObject('data.csv', 'r');
$csv->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
foreach ($csv as $row) {
// $row 已是陣列:['欄位1', '欄位2', ...]
echo implode(' | ', $row) . "\n";
}
?>
<?php
// 讀取遠端文字檔
$lines = @file('https://example.com/robots.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines !== false) {
foreach ($lines as $line) {
echo "{$line}\n";
}
} else {
echo "遠端讀取失敗";
}
?>
| 方法 | 記憶體 | 速度 | 適用場景 |
|---|---|---|---|
file() | O(N) | 快(單次系統呼叫) | < 10MB 文字檔、設定檔、小資料集 |
fgets() 迴圈 | O(1) | 中 | 大檔案、日誌、串流處理 |
SplFileObject | O(1) | 中 | 物件導向、CSV、需隨機存取行號 |
stream_get_contents() | O(N) | 最快 | 需整份字串、小檔案 |
根據檔案大小與處理需求選擇正確工具,file() 方便但有體積上限,大檔案必須改用串流式讀取。