1
1st line
2nd line
...
//append here
last line

I have a php script use file put content append

I need to append between last 2nd line & last line?

anyone know how to achieve this?

user2178521
  • 833
  • 1
  • 14
  • 26

1 Answers1

4

Alternatively, you could use file(), and outputs an array. From there you can determine the second to the last line. Consider this example:

$replacement = "Hello World";
$contents = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$size = count($contents);
$contents[$size-2] = $replacement; // point it to the second last line and assign
$temp = implode("\n", $contents);
file_put_contents('file.txt', $temp);
user1978142
  • 7,946
  • 3
  • 17
  • 20