Jump to content

Add to start of file


tommy20

Recommended Posts

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

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

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.