I have a large file "file.txt"
I want to read one specific line from the file, change something and then write that line back into its place in the file.
Being that it is a large file, I do not want to read the entire file during the reading or writing process, I only want to access that one line.
This is what I'm using to retrieve the desired line:
$myLine = 100;
$file = new SplFileObject('file.txt');
$file->seek($myLine-1);
$oldline = $file->current();
$newline=str_replace('a','b',$oldline);
Now how do I write this $newline to replace the old line in the file?
You could use this function:
function injectData($file, $data, $position) {
$temp = fopen('php://temp', "rw+");
$fd = fopen($file, 'r+b');
fseek($fd, $position);
stream_copy_to_stream($fd, $temp); // copy end
fseek($fd, $position); // seek back
fwrite($fd, $data); // write data
rewind($temp);
stream_copy_to_stream($temp, $fd); // stich end on again
fclose($temp);
fclose($fd);
}
I got it from: PHP what is the best way to write data to middle of file without rewriting file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With