Write to specific line in PHP Write to specific line in PHP php php

Write to specific line in PHP


you can use file to get the file as an array of lines, then change the line you need, and rewrite the whole lot back to the file.

<?php$filename = getcwd() . "/stats/stats.txt";$line_i_am_looking_for = 123;$lines = file( $filename , FILE_IGNORE_NEW_LINES );$lines[$line_i_am_looking_for] = 'my modified line';file_put_contents( $filename , implode( "\n", $lines ) );


This should work. It will get rather inefficient if the file is too large though, so it depends on your situation if this is a good answer or not.

$stats = file('/path/to/stats', FILE_IGNORE_NEW_LINES);   // read file into array$line = $stats[$offset];   // read linearray_splice($stats, $offset, 0, $newline);    // insert $newline at $offsetfile_put_contents('/path/to/stats', join("\n", $stats));    // write to file


I encountered this today and wanted to solve using the 2 answers posted but that didn't work. I had to change it to this:

<?php$filepathname = "./stats.txt";$target = "1234";$newline = "after 1234";$stats = file($filepathname, FILE_IGNORE_NEW_LINES);   $offset = array_search($target,$stats) +1;array_splice($stats, $offset, 0, $newline);   file_put_contents($filepathname, join("\n", $stats));   ?>

Because these lines don't work since the arg of the array is not an index:

$line = $stats[$offset]; $lines[$line_i_am_looking_for] = 'my modified line';

Had to add that +1 to have the new line under the searched text.