Jump to content

How to write to CSV file ?


tmyonline

Recommended Posts

Hi guys,

 

I need to write the output of my program to a CSV file.  Here's my code:

 

foreach ($groups as $group) {

  $fp = fopen('result.csv', 'w');

  fputcsv($fp, split(',', $group));

}

 

The above code does write the result to CSV (result.csv file) but what happens is that it always overwrites the previous result.  Consequently, only the last line appears in the result.csv file.  How do I make it so that the second time it writes to CSV, it will start on a new line instead of overwriting the previous line ?  Thanks guys.

Link to comment
https://forums.phpfreaks.com/topic/156844-how-to-write-to-csv-file/
Share on other sites

Thanks Ken.

 

Oh yes, I don't need to open the file every time through the loop.

 

I did as you said, using the implode():

 

  fputcsv($fp,implode(',', $group));

 

but it caused errors.  It said "Invalid arguments passed in line 28" which is the line above.

 

Does the implode() function resolve the new line issue ?  Rightnow, everytime it writes to CSV, it does not start on a new line, instead it overwrites the existing line.  Thanks a lot.

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.