Forum Moderators: coopster

Message Too Old, No Replies

fopen/write

         

mtmtmt

11:15 am on May 11, 2006 (gmt 0)

10+ Year Member



I am writing a script that will take form data and save it to a text file. now... I want the newly submitted data to be added to the first line of the text file instead of the last line. How can I do this? I have tried fopen("file.txt", "r+"); but this erases all the text in the file and writes the new text.

ahmedtheking

11:43 am on May 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Do this:

Open the file: $file = implode("",file(path to file));

Then, you get the data from your form and stick it on the front:
$newdata = $formdata.$file;

Then you write it to the file!

mtmtmt

12:03 pm on May 11, 2006 (gmt 0)

10+ Year Member



Could you elaborate? Do I replace fopen with implode?

This is the code im using

$headline = "<tr><td>".$_POST['headline']."</td></tr>";
$handle0 = fopen("headlines.txt", "r+");
fwrite($handle0, $headline);
fclose($handle0);

coopster

2:04 pm on May 11, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



ahmedtheking is explaining the most common approach to writing new content to a text file when it needs to be anywhere except appended to the end of the original file contents. You read the string into memory, manipulate the string, and then write the contents back out entirely as new data. file_get_contents() [php.net] is a great function for reading the entire file in as a string, by the way.

ahmedtheking

2:15 pm on May 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ok this is your code:

$headline = "<tr><td>".$_POST['headline']."</td></tr>";
$handle0 = fopen("headlines.txt", "r+");
fwrite($handle0, $headline);
fclose($handle0);

This is how I'd do it:

$handle0 = implode("",file("headlines.txt"));

$headline = "....";

$handle1 = fopen("headlines.txt", "w+");
fwrite($handle1, $headline."\n".$handle0);
fclose($handle1);

This will then add $headline on the first line of your file.