I need to write data to a csv file. As long as the data doesn't contain commas, it works fine. But if it does, the format of the csv file is corrupted due to the extra commas. Here is some test code I wrote to show the problem. $csvdata = "col1,col2,col3" . "\n"; $csvdata .= "bob" . " , " ; $csvdata .= "sally" . " , " ; $csvdata .= "tom, sue" . " , " ; $csvdata .= "\n"; $fp = fopen( 'testfile.csv' , "w" ); fwrite($fp,$csvdata); fclose($fp); PHP: The result is: col1 col2 col3 bob sally tom sue where sue is in the fourth column. Would someone please point out how to handle the extra commas?
The problem is the parser that reads your csv file. You need to: 1. Either modify the parser to ignore commas within the double-quotes. 2. Or use a different field-separator, for example pipe | or single-quote ' or @ I'm an expert programmer, feel free to hire me for any work. Here's some info: http://forums.digitalpoint.com/showthread.php?t=1791552
use str_replace comma by zzzzzzzzzzzz then while displaying it again replace zzzzzzzzzzzz by comma Regards Alex
Thank you both for the responses. But the file is being read with excel by different users so creating a file that all of the users can only read if they alter their excel settings isn't a workable solution. There must be a way to create a file that doesn't depend upon the user having to adjust their settings. Does anyone have any other suggestions?
The following works. I thought I would post it here in case someone else needs to know how to do it. $csvdata = array(); $csvdata[] = array("col1","col2","col3"); $csvdata[] = array("bob","sally","bob, sally"); $fp = fopen( 'testfile.csv' , "w" ); foreach ($csvdata as $record) { fputcsv($fp, $record); } fclose($fp); PHP: