简体   繁体   中英

PHP write in file in specific location

Imagine I have a TXT file with the following contents:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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