文字檔常用於簡易資料儲存、快取或日誌。本文示範如何將陣列寫入 TXT、按行讀取回陣列、以及刪除指定行的實作方法。
$keys = range(1, 999);
$file = fopen('key_11010000.txt', 'w');
foreach ($keys as $key) {
fwrite($file, "$key\r\n");
}
fclose($file);
$f1 = fopen('key_11010000.txt', 'r');
while (!feof($f1)) {
$line = fgets($f1);
$line = trim($line);
$arr[] = $line;
}
fclose($f1);
$keys = array_filter($arr); // 移除空行
var_dump($keys);
PHP 無直接「刪除檔案中間某行」函式,常見做法是讀全檔 → 陣列操作 → 重寫檔案:
function deleteLine($filePath, $lineNumber) { // 行號從 1 開始
if (!file_exists($filePath)) return false;
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lineNumber < 1 || $lineNumber > count($lines)) return false;
unset($lines[$lineNumber - 1]);
$lines = array_values($lines); // 重排索引
return file_put_contents($filePath, implode("\r\n", $lines) . "\r\n");
}
// 使用:刪除第 5 行
deleteLine('key_11010000.txt', 5);
fgets)而非 file() 一次載入全部,避免記憶體耗盡。rename() 覆蓋,確保原子性。flock())或改用 SQLite/Redis。掌握 fopen/fgets/fwrite 基礎操作,配合陣列處理,即可靈活完成 TXT 檔案的讀寫與行級編輯。