简体   繁体   English

创建CSV文件时,是否需要转义某些字符?

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

I am generating a CSV file from Ruby. 我正在从Ruby生成CSV文件。 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? 另外,如何将CSV插入MySQL? Would you need to use something like PHP's mysql_real_escape_string? 你需要使用像PHP的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. 编写CSV数据很简单,最简单的方法是用双引号替换双引号的每个实例,然后用双引号括起整个事物。 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. 解析CSV要复杂得多,特别是如果您尝试处理各种形式的格式错误的数据,在这种情况下,您几乎肯定希望使用现有模块。

Use FasterCSV. 使用FasterCSV。 Do not roll your own CSV generation. 不要滚动自己的CSV代。

http://fastercsv.rubyforge.org/ http://fastercsv.rubyforge.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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