Search code examples
phpsplfileobject

Append string to a file at certain position


say we have this file test.txt:

{}

And we want to add text between { and }.

I tried this:

$f = new SplFileObject($filepath, 'r+');
$f->fseek(1);
$f->fwrite('test');

but the output is {test, I tried also other modes like w+ (result-> test), a+ (result-> {}test

EDIT: forgot to tell that I dont want to load all the contents of the file to the memory, thats why I using SplFileObject


Solution

  • You have to load the file into memory for this kind of transformation—at least a portion of the file. That's what memory is for. You could read one file and write another with modifications to avoid keeping the entire file in memory.

    If necessary, then delete the old file and rename the new file to the old.