Escaping for CSV

前端 未结 4 1691
说谎
说谎 2020-12-08 10:38

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 follow

4条回答
  •  余生分开走
    2020-12-08 10:58

    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:

    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.

提交回复
热议问题