3

I use the following code to get data from a form and save it as csv.

$cvsData = $name . "," . $address . "\n";

$fp = fopen("file.csv", "a");

if ($fp) {
    fwrite($fp, $cvsData); // Write information to the file
    fclose($fp); // Close the file
}

When someone enters a comma or line break in address field it breaks the formatting. So how can i escape it so that the whole address stays in the same field ?

1
  • 1
    start using PHP's built-in fputcsv() functions for writing csv files rather than building your own $cvsData line... then, at least, you don't need to worry about commas in your data Commented Feb 10, 2012 at 7:28

2 Answers 2

5

Put each data item inside quotation marks. A pair of quotation marks inside a quoted value signifies a single quotation mark. e.g.

"Daniel Norton","Congress Ave.
Austin (""Keeping it weird""), TX"

Referring to your example:

$data = str_replace('"','""',$data);
$address = str_replace('"','""',$address);
$cvsData = "\"$data\",\"$address\"\n";

Better still, just use the PHP function fputcsv.

fputcsv($fp,array($data,$address));
Sign up to request clarification or add additional context in comments.

1 Comment

I have added more detail, using your example.
0

CSV is totally dependent on the software used to read it.

Have a look at http://www.csvreader.com/csv_format.php for some details on how certain programs expect CSV data.

I have created a CSV class that can handle most of these situations. You might want to have a look at it.

https://gist.github.com/1786683

And to answer your question, using that class you could

$csv = CSV::newExcel();
$cvsData = $csv->row($name, $address);
// etc...

Comments

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.