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.
Yes. You can import double quotation marks using CSV files and import maps by escaping the double quotation marks. To escape the double quotation marks, enclose them within another double quotation mark.
Re: Handling 'comma' in the data while writing to a CSV. So for data fields that contain a comma, you should just be able to wrap them in a double quote. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.
Actually, the only value to escape is double quotes symbol. All other cell content gets into it and displayed correctly in Excel. Checked with various versions of Excel and ODBC CSV parsers in Cyrillic locale under Windows.
Since CSV files use the comma character "," to separate columns, values that contain commas must be handled as a special case. These fields are wrapped within double quotation marks. The first double quote signifies the beginning of the column data, and the last double quote marks the end.
Use fputcsv()
to write, and fgetcsv()
to read.
fputcsv()
is not always necessary especially if you don't need to write any file but you want to return the CSV as an HTTP response. All you need to do is to double quote each value and to escape double quote characters repeating a double quote each time you find one.
Here a few examples:
hello -> "hello" this is my "quote" -> "this is my ""quote""" catch 'em all -> "catch 'em all"
As you can see the single quote character doesn't need any escaping.
Follows a full working example:
<?php $arrayToCsvLine = function(array $values) { $line = ''; $values = array_map(function ($v) { return '"' . str_replace('"', '""', $v) . '"'; }, $values); $line .= implode(',', $values); return $line; }; $csv = []; $csv[] = $arrayToCsvLine(["hello", 'this is my "quote"', "catch 'em all"]); $csv[] = $arrayToCsvLine(["hello", 'this is my "quote"', "catch 'em all"]); $csv[] = $arrayToCsvLine(["hello", 'this is my "quote"', "catch 'em all"]); $csv = implode("\r\n", $csv);
If you get an error is just because you're using an old version of PHP. Fix it by declaring the arrays with their old syntax and replacing the lambda function with a classic one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With