简体   繁体   English

PHP在特定位置写入文件

[英]PHP write in file in specific location

Imagine I have a TXT file with the following contents: 想象一下,我有一个包含以下内容的TXT文件:

Hello
How are you
Paris
London

And I want to write beneath Paris, so Paris has the index of 2, and I want to write in 3. 我想在巴黎下面写东西,所以巴黎的索引为2,我想写3。

Currently, I have this: 目前,我有这个:

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

$contents = file($fileName);
$contents[$lineNumber] = $changeTo;

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

But it only modifies the specific line. 但是它仅修改特定的行。 And I don't want to modify, I want to write a new line and let the others stay where they are. 而且我不想修改,我想写一个新行,让其他人留在原处。

How can I do this? 我怎样才能做到这一点?

Edit : Solved. 编辑 :已解决。 In a very easy way: 以一种非常简单的方式:

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

You need to parse the contents of the file, place the contents in a new array and when the line number you want comes up, insert the new content into that array. 您需要解析文件的内容,将内容放置在新的数组中,然后在出现所需的行号时,将新内容插入该数组中。 And then save the new contents to a file. 然后将新内容保存到文件中。 Adjusted code below: 调整后的代码如下:

$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