PHP to CSV line break issue
12,892
Put each data item inside quotation marks. A pair of quotation marks inside a quoted value signifies a single quotation mark. e.g.
"Daniel Norton","Congress Ave.
Austin (""Keeping it weird""), TX"
Referring to your example:
$data = str_replace('"','""',$data);
$address = str_replace('"','""',$address);
$cvsData = "\"$data\",\"$address\"\n";
Better still, just use the PHP function fputcsv.
fputcsv($fp,array($data,$address));
Author by
Ajay
Updated on June 27, 2022Comments
-
Ajay almost 2 years
I use the following code to get data from a form and save it as csv.
$cvsData = $name . "," . $address . "\n"; $fp = fopen("file.csv", "a"); if ($fp) { fwrite($fp, $cvsData); // Write information to the file fclose($fp); // Close the file }
When someone enters a comma or line break in address field it breaks the formatting. So how can i escape it so that the whole address stays in the same field ?
-
Mark Baker about 12 yearsstart using PHP's built-in fputcsv() functions for writing csv files rather than building your own $cvsData line... then, at least, you don't need to worry about commas in your data
-
-
danorton about 12 yearsI have added more detail, using your example.