PhP newb question:writing text to a file by insertion, not overwriting

Aleran

Registered
I just started learning php and I've come across a problem I can't find the solution to anywhere. All I want to do is scan through a file until I read a key string and then write text there. I have been able to scan through the file to the point needed, but when I then write to the file it replaces the text in the buffer as opposed to inserting the text where the file pointer is. I was using fopen and fwrite. Is there maybe some mode for fopen I need to use which I don't know about? I was using r+.
 
If you are trying to do what I think you are, you are kind of stuck. Text files in PHP are not much more complex than string data, so you can't really insert data without segmenting it first or overwriting the existing data.

If you know your data file is not going to be very large, simply load the entire file into a single variable, manipulate it as a string and then overwrite the old file. If you use regular expressions, there is really no faster way to do it.

If you can *imagine* the file becoming too big to be loaded into memory, consider creating a temp file (w+), write the new data and the old data's tail into the temp file, fseek back to your insertion point in the original file, rewind temp, write the contents of temp back into the original and then destroy temp. This technique is pretty fast and uses practically no memory.
 
Thanks for the response. I was afraid this was the only method. I mean its not terribly hard to implement, it just seemd kind of sloppy so I was hoping php simply had a way to insert data. Ah well, for my purposes the text file will be more than (less than?) small enough to just overwrite the entire thing. Thanks again.
 
Back
Top