tommy20 Posted November 7, 2009 Share Posted November 7, 2009 I have a file which I open through $handle = fopen("details/horselistfile.txt", "a+"); fwrite($handle, "\n$horsearray\n"); fclose($handle); I want to add to the start of the file by changing to $handle = fopen("details/horselistfile.txt", "r+"); fwrite($handle, "\n$horsearray\n"); fclose($handle); But it just pastes over the last entry that I had. How do you prepend a file Link to comment https://forums.phpfreaks.com/topic/180657-add-to-start-of-file/ Share on other sites More sharing options...
.josh Posted November 7, 2009 Share Posted November 7, 2009 There is no built-in way to prepend something to a file. You have to open your file, read the contents into a variable or array, concat your new stuff to the front of the var/array,and then write the whole thing back to the file. That's not really all that convenient if your file is large. If your file is large I suggest you look into using a database instead. edit: I suppose if it's a large file and a db isn't an option, you can write your new info to a temp file and then read your existing file 1 line at a time, appending the info to the temp file 1 line at a time, and then rename your temp file to the existing file. Link to comment https://forums.phpfreaks.com/topic/180657-add-to-start-of-file/#findComment-953151 Share on other sites More sharing options...
Alex Posted November 7, 2009 Share Posted November 7, 2009 You can just do: file_put_contents('details/horselistfile.txt', $horsearray . file_get_contents('details/horselistfile.txt')); file_get_contents() and file_put_contents() do the same thing as fopen(), fread()/fwrite and fclose(), they just make things easier for you. Link to comment https://forums.phpfreaks.com/topic/180657-add-to-start-of-file/#findComment-953152 Share on other sites More sharing options...
tommy20 Posted November 7, 2009 Author Share Posted November 7, 2009 Do you have a script that would prepend a line to a file. The file contains a few lines each on a separate line Link to comment https://forums.phpfreaks.com/topic/180657-add-to-start-of-file/#findComment-953317 Share on other sites More sharing options...
Daniel0 Posted November 7, 2009 Share Posted November 7, 2009 Do you have a script that would prepend a line to a file. The file contains a few lines each on a separate line See: You can just do: file_put_contents('details/horselistfile.txt', $horsearray . file_get_contents('details/horselistfile.txt')); file_get_contents() and file_put_contents() do the same thing as fopen(), fread()/fwrite and fclose(), they just make things easier for you. Link to comment https://forums.phpfreaks.com/topic/180657-add-to-start-of-file/#findComment-953322 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.