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 .

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

$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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.