Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a specific line in a large file (PHP)

Tags:

php

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?

like image 829
Fomo Avatar asked Jul 20 '26 01:07

Fomo


1 Answers

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

like image 58
jankal Avatar answered Jul 21 '26 16:07

jankal