Reputation: 299
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"]);
Upvotes: 4
Views: 6494
Reputation: 659
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));
Upvotes: 4
Reputation: 363
You can escape coma like this:
$_POST["field"] = str_replace(",", "\,", $_POST["field"]);
Or you can put string in quotes
$_POST["field"] = "'".$_POST["field"]."'";
Upvotes: 0
Reputation: 1958
Use html encoding for instant relief , but still my recommendation to use phpExcel
$comma=",";
$_POST["field"] = str_replace(",", $comma, $_POST["field"]);
Upvotes: 5
Reputation: 316
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
Upvotes: -1