繁体   English   中英

PHP在特定位置写入文件

[英]PHP write in file in specific location

想象一下,我有一个包含以下内容的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));

您需要解析文件的内容,将内容放置在新的数组中,然后在出现所需的行号时,将新内容插入该数组中。 然后将新内容保存到文件中。 调整后的代码如下:

$fileName = 'file.txt';
$lineNumber = 3;
$changeTo = "the changed line\n";

$contents = file($fileName);

$new_contents = array();
foreach ($contents as $key => $value) {
  $new_contents[] = $value;
  if ($key == $lineNumber) {
    $new_contents[] = $changeTo;
  }
}

file_put_contents($fileName, implode('',$new_contents));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM