1

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));
Giacomo1968
  • 23,903
  • 10
  • 59
  • 92
user2902515
  • 193
  • 1
  • 1
  • 11
  • use [array_splice()](http://www.php.net/function.array-splice) to inject new entries into your $contents array – Mark Baker Nov 21 '13 at 16:42
  • See http://stackoverflow.com/questions/3797239/insert-new-item-in-array-on-any-position-in-php – jszobody Nov 21 '13 at 16:43
  • http://stackoverflow.com/questions/2149233/how-to-add-an-array-value-to-the-middle-of-an-array is more appropriate, I think @jszobody – m59 Nov 21 '13 at 16:44
  • you should write your answer as an answer - not in the question :) -- also: this doesn't scale. reading in a whole file only to add a line? don't know php but that looks bad. up voting to see if there is a better way – Daij-Djan Mar 01 '14 at 09:57

1 Answers1

2

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));
Giacomo1968
  • 23,903
  • 10
  • 59
  • 92