Tanmai
Tanmai

Reputation: 21

saving data in csv file using php

I am taking data from a form and saving it in a CSV file using PHP. My one field in the form contain the comma in it, i.e., between two words a comma is there and I need to store that in the CSV file with a comma. But when I an saving it the values left and right to comma are stored in different rows. How can I do it? My code is:

enter code here
<?php
//read data from form
$food = filter_input(INPUT_POST, "food"); 
$output = $food . "\n";
$fp="input.csv";
if (file_exists($fp)) {
file_put_contents($fp, $output, FILE_APPEND);
}
else {
file_put_contents($fp, $output);
}
?>

Upvotes: 0

Views: 1842

Answers (1)

Scruff
Scruff

Reputation: 111

By default, CSV files use the comma as the field separater, so if the value contains any commas, it needs to be quoted in the same way it should be if it contains spaces. If using "file_put_contents", you need to do that manually with something like this:

<?php
//read data from form
$food = filter_input(INPUT_POST, "food"); 
$output = preg_match('/[, ]/', $food) ? "\"$food\"\n" : "$food\n";
file_put_contents('input.csv', $output, FILE_APPEND);
?>

The "preg_match" function checks $food for commas or spaces and if any are found, $food is double quoted and the linefeed is added, otherwise only the linefeed is added.

Note also that you don't need to check if the file already exists, because if it doesn't, the file_put_contents function automatically creates it whether or not you use the FILE_APPEND flag.

But a much better solution would be to use the CSV specific functions which do any necessary quoting or escaping for you automatically:

<?php
//read data from form
$food = filter_input(INPUT_POST, "food"); 
$fields = array($food);
$fp = fopen('input.csv', 'a+');
fputcsv($fp, $fields);
fclose($fp);
?>

Using fopen in "a+" mode causes it to act the same as file_put_contents does with the FILE_APPEND flag. So there's no need to check if the file exists beforehand here either.

Upvotes: 1

Related Questions