Php – Escaping for CSV

PHPregex

I need to store a string in a MySQL database. The values will later be used in a CSV. How do I escape the string so that it is CSV-safe? I assume I need to escape the following: comma, single quote, double quote.

PHP's addslashes function does:

single quote ('), double quote ("), backslash () and NUL (the NULL byte).

So that won't work. Suggestions? I'd rather not try to create some sort of regex solution.

Also, I need to be able to unescape.

Best Answer

Use fputcsv() to write, and fgetcsv() to read.

Related Topic