4

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?

0

1 Answer 1

1

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

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.