Top of the list

I have a form that collects data from a few different fields and saves it to a csv file in the normal manner of newest record at the bottom of the csv. However what I really need it to do is write the data to the top of the csv if possible. I have a page that manages the data and saves it to the csv for me. The script is listed here. Any help would be awesome and much appreciated.

[php]

<?php $mm = $_POST['mm']; $dd = $_POST['dd']; $yy = $_POST['yy']; $name = $_POST['name']; $comment = $_POST['comment']; $fp = fopen("datafeed/filetoread.csv", "a"); $savestring = $mm . " " . $dd . " " . $yy . " " . $name . " " . $comment . "\n"; fwrite($fp, stripslashes($savestring)); fclose($fp); echo "

Your data has been saved

"; ?>

[/php]

There are also field headers on the first line of my csv that need to remain. So really the newest content would need to start on line 2 if that is possible. Thanks

Hi there,

Try the code provided below and see if it’s what you requested. I tested something like this in my personal environment and it appears to be working properly. Let me know if something is wrong with the code or if I can be of more assistance.

[php]<?php
$mm = $_POST[‘mm’];
$dd = $_POST[‘dd’];
$yy = $_POST[‘yy’];
$name = $_POST[‘name’];
$comment = $_POST[‘comment’];

$lines = file(‘datafeed/filetoread.csv’);
$fp = fopen(“datafeed/filetoread.csv”, “w+”);
$header = array_shift($lines);
$savestring = $header . $mm . " " . $dd . " " . $yy . " " . $name . " " . $comment . “\r\n”;
fwrite($fp, stripslashes($savestring));

foreach($lines as $line) fwrite($fp, “$line”);

fclose($fp);
echo “

Your data has been saved

”;
?>[/php]

Cheers!

Sponsor our Newsletter | Privacy Policy | Terms of Service