tmyonline Posted May 4, 2009 Share Posted May 4, 2009 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 More sharing options...
kenrbnsn Posted May 4, 2009 Share Posted May 4, 2009 Move the fopen outside of the loop. <?php $fp = fopen('result.csv','w'); foreach ($group as $group) fputcsv($fp,implode(',', $group)); ?> Ken Link to comment https://forums.phpfreaks.com/topic/156844-how-to-write-to-csv-file/#findComment-826179 Share on other sites More sharing options...
tmyonline Posted May 4, 2009 Author Share Posted May 4, 2009 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. Link to comment https://forums.phpfreaks.com/topic/156844-how-to-write-to-csv-file/#findComment-826203 Share on other sites More sharing options...
PFMaBiSmAd Posted May 4, 2009 Share Posted May 4, 2009 fputcsv does the implode for you. It expects the second parameter to be an array. Link to comment https://forums.phpfreaks.com/topic/156844-how-to-write-to-csv-file/#findComment-826273 Share on other sites More sharing options...
tmyonline Posted May 5, 2009 Author Share Posted May 5, 2009 Thanks guys. Link to comment https://forums.phpfreaks.com/topic/156844-how-to-write-to-csv-file/#findComment-826917 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.