1

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.

6
  • 1
    As long as you're wrapping the fields in quotes, everything should be fine. Where are you reading the files? Commented Oct 27, 2013 at 0:36
  • @Pekka When I am wrapping the fields / post variables of php in quotes, it is showing errors Commented Oct 27, 2013 at 0:41
  • What if you use tab delimited txt files? Commented Oct 27, 2013 at 0:46
  • @Pekka웃 ya it worked thanks! I hv written like this: '"'.$_POST['element_5'].'"'." Commented Oct 27, 2013 at 0:47
  • Suggest you use fputcsv() Commented Oct 27, 2013 at 0:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In you example, you have the delimiter and enclosure the wrong way around. The defaults are also " and , - so you can just do fputcsv( $file, $fields)
Thanks for pointing that out, I fixed the code in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.