0

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);
}
?>
1

1 Answer 1

1

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.

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

2 Comments

how to save 3-4 fields
The fputcsv function writes one row each time you call it. $fields is an array, with each element being one field in the csv file from left to right. So to write more than one field, simply add more items to the array. Use an empty string for fields that you need to skip.

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.