coder
coder

Reputation: 299

PHP: Write comma to csv file

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

Answers (4)

Orry
Orry

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

Bukashk0zzz
Bukashk0zzz

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

Rohit Kumar
Rohit Kumar

Reputation: 1958

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

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

Upvotes: 5

Dannn
Dannn

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

Related Questions