简体   繁体   中英

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

I am generating a CSV file from Ruby. The problem is a column string will contain double quotes, single quotes. How can I escape 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 comma (and no space), and written into a file.

Additionally, how do you insert CSV into MySQL? Would you need to use something like PHP's mysql_real_escape_string?

Writing CSV data is easy, the simplest way is to replace every instance of a double quote with 2 double quotes and then surround the whole thing in double quotes. Alternatively, if your data does not contain double quotes, commas, carriage returns, linefeeds, or leading/trailing space, you don't have to surround the data with quotes or worry about escaping. You can find more information here .

Parsing CSV is much more complex, especially if you try to handle various forms of malformed data out there, in this case you almost certainly want to use an existing module.

Use FasterCSV. Do not roll your own CSV generation.

http://fastercsv.rubyforge.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM