Properly escape a double quote in CSV
Solution 1:
Use 2 quotes:
"Samsung U600 24"""
Solution 2:
Not only double quotes, you will be in need for single quote ('
), double quote ("
), backslash (\
) and NUL (the NULL byte).
Use fputcsv()
to write, and fgetcsv()
to read, which will take care of all.
Solution 3:
I have written in Java.
public class CSVUtil {
public static String addQuote(
String pValue) {
if (pValue == null) {
return null;
} else {
if (pValue.contains("\"")) {
pValue = pValue.replace("\"", "\"\"");
}
if (pValue.contains(",")
|| pValue.contains("\n")
|| pValue.contains("'")
|| pValue.contains("\\")
|| pValue.contains("\"")) {
return "\"" + pValue + "\"";
}
}
return pValue;
}
public static void main(String[] args) {
System.out.println("ab\nc" + "|||" + CSVUtil.addQuote("ab\nc"));
System.out.println("a,bc" + "|||" + CSVUtil.addQuote("a,bc"));
System.out.println("a,\"bc" + "|||" + CSVUtil.addQuote("a,\"bc"));
System.out.println("a,\"\"bc" + "|||" + CSVUtil.addQuote("a,\"\"bc"));
System.out.println("\"a,\"\"bc\"" + "|||" + CSVUtil.addQuote("\"a,\"\"bc\""));
System.out.println("\"a,\"\"bc" + "|||" + CSVUtil.addQuote("\"a,\"\"bc"));
System.out.println("a,\"\"bc\"" + "|||" + CSVUtil.addQuote("a,\"\"bc\""));
}
}