【发布时间】:2013-12-06 06:25:59
【问题描述】:
假设我有一个包含以下内容的 TXT 文件:
Hello
How are you
Paris
London
我想写在巴黎下面,所以巴黎的索引是 2,我想写在 3 中。
目前,我有这个:
$fileName = 'file.txt';
$lineNumber = 3;
$changeTo = "the changed line\n";
$contents = file($fileName);
$contents[$lineNumber] = $changeTo;
file_put_contents($fileName, implode('',$contents));
但它只修改特定的行。而且我不想修改,我想写一个新行,让其他人留在原地。
我该怎么做?
编辑:已解决。以一种非常简单的方式:
$contents = file($filename);
$contents[2] = $contents[2] . "\n"; // Gives a new line
file_put_contents($filename, implode('',$contents));
$contents = file($filename);
$contents[3] = "Nooooooo!\n";
file_put_contents($filename, implode('',$contents));
【问题讨论】:
-
使用 array_splice() 将新条目注入您的 $contents 数组
-
stackoverflow.com/questions/2149233/… 比较合适,我觉得@jszobody
-
你应该把你的答案写成答案——而不是在问题中:)——另外:这不成比例。读取整个文件只是为了添加一行?不知道php,但看起来很糟糕。投票看看是否有更好的方法