When you open the file you select the write mode. 'r' is read, 'w' is write, 'a' is append. In both the read and write modes, the file pointer is placed at the beginning of the file (meaning if you write data it will overwrite starting from the first byte in the file). In append mode, the file pointer is put at the end of the file, so you can add data on to the end of the file. Be careful using the overwrite modes; if you're writing less data than already exists, only bytes you explicitly write will be overwritten, and the rest will remain. To do this, look for the fopen("filename.txt", 'a') in your source and simply change it to fopen("filename.txt", 'w').
If you want to overwrite the entire file, the best solution is to first create the new file in a temporary location, write the new data to it, then move it overtop of the old file. The reason for this is that the old data will only be overwritten if the PHP process succeeds completely, otherwise the PHP script may fail once the file has been cleared but before the data is fully written. Something like the following would be a good solution.
$dest_file = "file.txt";
unlink(TMP_FILENAME); // delete any stale temporary files
$fp = fopen(".tmp.yourscript", "w"); // open the file and create it
fwrite($fp, "This is some test data.\n"); // replace with your processing and file writing code as normal
Mr Confused, I believe that a different approach to logic might solve your problem. Instead of reading the file from the very top, why don't you start reading it at the end of the file?
You can take a look at www.php.net/fseek and use that function to suit your reading needs.
I believe it's much less overhead than finding a way to write at the top of the file instead the natural way (append new content at the end).