Reputation: 193
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));
Upvotes: 1
Views: 2739
Reputation: 26066
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));
Upvotes: 2