Insert content into a file using php

Friday, March 20, 2009 | |

I wanted to insert a string of new content into an existing text file and I was having a hard time at it, but I figured it out, this is how I did it.

Instead of fooling around moving the pointer around I read the existing file in two parts.

  • First part
  • Second Part
Then I wrote my new information to a string and here is the trick, you write all three strings, the first part, the new information, and then the second part, all at once back into the existing file. The outcome looks like.
  • First Part
  • New Information
  • Second Part
Below is an example, it read in the first 10 characters then inserts the new information, then the rest of the file.

$file1 = "example.txt"; // example.txt = file1
$fh = fopen($file1, "r"); //open file1 using read
$fcontent1 = fread($fh, 10); //read the first 10 lines of file1
$fcontent = fread($fh, filesize($file1)); //read the rest of file1 save as fcontent
$newcontent = " new content "; //write new content
$towrite = "$fcontent1 $newcontent $fcontent"; //now save the first part the first 10 characters in fcontent1, then your new content, then since below our pointer will have moved, you can write what is the rest of the origional file was.

fclose($fh); //close the file
$fh2 = fopen('example.txt', 'w+'); //open it up again using write+
fwrite($fh2, $towrite); //and write the new file

fclose($fh2); //close the file