需求:讀取文字檔、修改特定行、寫回檔案。本文提供簡潔實作並說明大檔案處理注意事項。
<?php
$file_path = '123.txt';
// 1. 讀取整個檔案
$content = file_get_contents($file_path);
if ($content === false) {
die("無法讀取檔案: $file_path");
}
// 2. 按換行分割成陣列
$lines = explode("\n", $content);
// 3. 替換指定行 (第 13 行,索引 12)
$target_line = 12; // 0-based index
if (isset($lines[$target_line])) {
$lines[$target_line] = "123 - 已修改於 " . date('Y-m-d H:i:s');
} else {
die("行號超出範圍: 第 " . ($target_line + 1) . " 行不存在");
}
// 4. 合併回字串
$new_content = implode("\n", $lines);
// 5. 寫回檔案
if (file_put_contents($file_path, $new_content) === false) {
die("寫入失敗,請檢查權限");
}
echo "第 " . ($target_line + 1) . " 行已更新";
?>
<?php
/**
* 替換文字檔指定行
* @param string $file_path 檔案路徑
* @param int $line_num 行號 (1-based,人類直覺)
* @param string $new_content 新內容
* @param string $eol 換行符 (\n, \r\n, \r)
* @return bool
*/
function replace_file_line($file_path, $line_num, $new_content, $eol = "\n") {
if (!is_file($file_path) || !is_readable($file_path) || !is_writable($file_path)) {
return false;
}
if ($line_num < 1) return false;
$lines = file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// 注意: FILE_IGNORE_NEW_LINES 會移除換行符,適合純文字處理
$index = $line_num - 1;
if (!isset($lines[$index])) return false;
$lines[$index] = $new_content;
// 寫入時加回換行符
return file_put_contents($file_path, implode($eol, $lines) . $eol) !== false;
}
// 使用範例
if (replace_file_line('config.txt', 5, 'debug_mode = true')) {
echo "第 5 行已更新為 debug_mode = true";
} else {
echo "更新失敗:檔案不存在、行號錯誤或權限不足";
}
?>
<?php
function replace_large_file_line($source, $dest, $line_num, $new_content) {
$fp_in = fopen($source, 'r');
$fp_out = fopen($dest, 'w');
if (!$fp_in || !$fp_out) return false;
$current_line = 0;
while (($line = fgets($fp_in)) !== false) {
$current_line++;
if ($current_line === $line_num) {
fwrite($fp_out, $new_content . "\n");
} else {
fwrite($fp_out, $line);
}
}
fclose($fp_in);
fclose($fp_out);
// 原子性替換
return rename($dest, $source);
}
// 使用
replace_large_file_line('huge.log', 'huge.log.tmp', 100000, 'NEW LINE CONTENT');
?>
| 函式 | 用途 | 特性 |
|---|---|---|
| file_get_contents | 一次讀全檔 | 簡單、小檔案適用 |
| file() | 讀成陣列 | 自動分行、可忽略換行符 |
| fopen/fgets | 逐行讀取 | 記憶體效率高、大檔案必備 |
| file_put_contents | 一次寫入 | 原子性 (Linux)、支援 LOCK_EX |
| fwrite | 流式寫入 | 大檔案、需自行管理 |
flock() 或寫暫存檔再 rename