Jump to content

Fputcsv() Is Writing To My File But Erasing The Previous Data


s4surbhi2218

Recommended Posts

HI all,

I am using php code to write into my csv file , its able to write successfully but every time i run my code the older data is lost and csv file is left with data which only the current run contains.

I used this

 

<?

$list = array (

array('aaa', 'bbb', 'ccc', 'dddd'),

array('123', '456', '789'),

array('"aaa"', '"bbb"')

);

 

$fp = fopen('test.txt', 'w');

 

foreach ($list as $fields) {

fputcsv($fp, $fields);

}

 

fclose($fp);

?>

 

Any suggestions???

Many thanks .

fputcsv() writes out to the csv name given, it does not append data to it. The only way that pops into my head would be to load in the original csv, and then append the $list onto the old contents before writing it all back to the original csv. This does however seem to me to be a somewhat bloated way of doing things, but I'm not well versed in the manipulation of files with php, so there will probably be a better suggestion.

$fp = fopen('test.txt', 'w');

 

w - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

 

It's not the fputcsv that is wiping out your file, it's the fact that you're using mode 'w' when you open it.  If you want to append the data to the file, use mode 'a':

a - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

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.