When creating a CSV file, do you need to avoid certain characters?

I am creating a CSV file from Ruby. The problem is that the row of the column will contain double quotes, single quotes. How can I avoid these things?

"Mary had a little so called \"lamb\"","34","none" "something is not \"right\"","23","none" 

Each column is enclosed in double quotes, followed by a comma (and without a space), and written to a file.

Also, how do you embed CSV in MySQL? Will you need to use something like PHP mysql_real_escape_string?

+4
source share
2 answers

Writing CSV data is simple, the easiest way is to replace each instance of the double quotation mark with two double quotation marks, and then surround it all in double quotation marks. Alternatively, if your data does not contain double quotes, commas, carriage returns, line breaks or leading / trailing space, you do not need to surround the data with quotes or worry about escaping. You can find more information here .

CSV analysis is much more complicated, especially if you are trying to process various forms of distorted data there, in which case you almost certainly want to use the existing module.

+6
source

Use FasterCSV. Do not collapse your own CSV generation.

http://fastercsv.rubyforge.org/

+2
source

All Articles