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));
4
  • use array_splice() to inject new entries into your $contents array Commented Nov 21, 2013 at 16:42
  • See stackoverflow.com/questions/3797239/… Commented Nov 21, 2013 at 16:43
  • stackoverflow.com/questions/2149233/… is more appropriate, I think @jszobody Commented Nov 21, 2013 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 Commented Mar 1, 2014 at 9:57

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.