【问题标题】:PHP write in file in specific locationPHP在特定位置写入文件
【发布时间】: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));

【问题讨论】:

标签: php newline


【解决方案1】:

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

$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));

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多