4
votes

I've got a form which submits data to a csv file. When a user inputs a comma to a field, it destroys my csv structure. I want to convert inputted commas so that they can get displayed as a character.

I tried this:

$_POST["field"] = str_replace(",", "','", $_POST["field"]);
4
What are you using to generate the CSV file? - Jonnix
use phpExcel to produce result .. - Rohit Kumar
The correct CSV structure is that each column should be wrapped with double quotes, and then any double quotes inside to be escaped. - Jamie Bicknell
Instead of writing your own escaping and formatting mechanism, consider using fputcsv. - Mureinik
phpExcel is depricated for now ! see github.com/PHPOffice/PHPExcel below is right answer "use fputcsv() to write, and fgetcsv() to read the file" its a safe and correct way ! versus just replace POST, that can overflowed your serv - Vladimir Ch

4 Answers

4
votes

Use html encoding for instant relief , but still my recommendation to use phpExcel

$comma="&#44";
$_POST["field"] = str_replace(",", $comma, $_POST["field"]);
4
votes

You can use fputcsv() to write, and fgetcsv() to read the file, it automatically converts your string.

A simple example for writing the data:

$csv = fopen('file.csv', 'w');
$array = array($csv);
fputcsv($csv, $array);

And reading the data:

$csv = fopen('file.csv','r');
print_r(fgetcsv($csv));
0
votes

Probably not the best answer, but it does work.

You could replace the comma with a random string when inputting to the CSV as below:

$commastring = str_replace(",", "/zwdz/", $tempstring);

and then when you need to output the comma somewhere on your website (if a database website) you can do the opposite str_replace

0
votes

You can escape coma like this:

$_POST["field"] = str_replace(",", "\,", $_POST["field"]);

Or you can put string in quotes

$_POST["field"] = "'".$_POST["field"]."'";