0

I know fputcsv() is the best way for dealing with exporting to CSV, but I'm currently doing a quick modification to a PHP CSV export script, and the client doesn't want to change how it's being handled. (wants it fast!)

So right now, an array of the data is manually being created, each item manually enclosed in double-quotes, and added to the CSV file.

My question is, if you have data which already contains double quotes (i.e. "and he said "Yes""), then whats the best way of dealing with that? The extra quotes seem to break the CSV file.

2
  • 1
    use php function htmlspecialchars($text) export the text with quotes without breaking the code Commented Mar 17, 2014 at 15:14
  • 1
    Ninja Developers > what a bad advice if you ask me... why include HTML special characters in a CSV file ? That's not how you escape characters... Commented Mar 17, 2014 at 15:17

3 Answers 3

5

In CSV you can escape quotes by doubling them. Two quotes in the file mean a single quote in the string. So you could write a function like this to do it for you. The added advantage is that you can add specific other transformations if you need to.

function EscapeForCSV($value)
{
  return '"' . str_replace('"', '""', $value) . '"';
}

Note, this function also adds the surrounding quotes, so the value is a complete value to write out.

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

Comments

0

For escaping in the resulting CSV use double Quotes to escape them:

val1, val2, "and he said ""Yes"" "

The Result of the third value would be: and he said "Yes"

2 Comments

With this solution, wouldn't the 'Yes', now be surrounded by 2 sets of quotes on either side? Also, when you says "escape the existing quotes with backslashes" what are the existing quotes you're referring to?
Yes, on each side there would be two quotes. That's how the escaping works. I also edited my answer, forget the thing with the backlashes ;-)
0

that because the default of enclosure was "" if you want to export quotation mark, simply change enclosure value to , in order to change the default value of enclosure. fputcsv(file, datafield, delimiter, enclosure); //default enclosure is "" so its become like this fputcsv(file, datafield, delimiter, ",");

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.