简体   繁体   中英

How to add data (which includes commas) to CSV file through php form

I have created a form and able to add data to CSV on submit. But my code is such that the csv file is delimited by commas and so when I add comma in the form data, the php code separates it as another entry (column).

Here is my php code:

<?php 
$filename = "data.csv";
$string = $_POST['element_1'].",".$_POST['element_2'].",".$_POST['element_3'].",".$_POST['element_4_1']."-".$_POST['element_4_2']."-".$_POST['element_4_3'].",".$_POST['element_5']."\n";
if (file_exists($filename)) {
  $file = fopen($filename, "a");
  fwrite($file, $string);
} else {
   $file = fopen($filename, "a");
   fwrite($file, '"Name","Phone","No. of persons","Date","Venue"\n');
   fwrite($file, $string);
}
fclose($file);
?>

In the above code, Venue sometimes, takes 'commas'. But the code separates the Venue data into new columns.

So, is there any other way to enter data into excel sheet other that CSV or any code gimmick.

You can make your life easier by using fputcsv and fgetcsv .

fputcsv lets you specify the delimiter and enclosure you need. The big difference is that you must pass the fields as an array: each value of the array is a column value in the csv line.

So given a $fields array that contains your CSV line values:

$file = fopen( 'data.csv', 'a' );

fputcsv( $file, $fields, ',', '"' );

fclose( $file );

Important: the flag on fopen must be a in order to append to the file. If you use w you will overwrite the previous content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM