php 转义为 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6325613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:02:05  来源:igfitidea点击:

Escaping for CSV

phpregex

提问by StackOverflowNewbie

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 following: comma, single quote, double quote.

我需要在 MySQL 数据库中存储一个字符串。稍后将在 CSV 中使用这些值。如何转义字符串以使其对 CSV 安全?我假设我需要转义以下内容:逗号、单引号、双引号。

PHP's addslashesfunction does:

PHP 的addslashes功能是:

single quote ('), double quote ("), backslash () and NUL (the NULL byte).

单引号 (')、双引号 (")、反斜杠 () 和 NUL(空字节)。

So that won't work. Suggestions? I'd rather not try to create some sort of regex solution.

所以这行不通。建议?我宁愿不尝试创建某种正则表达式解决方案。

Also, I need to be able to unescape.

另外,我需要能够逃脱。

回答by Ignacio Vazquez-Abrams

Use fputcsv()to write, and fgetcsv()to read.

使用fputcsv()写,fgetcsv()阅读。

回答by Francesco Casula

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.

fputcsv()并不总是必要的,特别是如果您不需要写入任何文件但您想将 CSV 作为 HTTP 响应返回。您需要做的就是对每个值加双引号,并在每次找到双引号时对重复双引号的双引号字符进行转义。

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:

遵循一个完整的工作示例:

<?php

$arrayToCsvLine = function(array $values) {
    $line = '';

    $values = array_map(function ($v) {
        return '"' . str_replace('"', '""', $v) . '"';
    }, $values);

    $line .= implode(',', $values);

    return $line;
};

$csv = [];
$csv[] = $arrayToCsvLine(["hello", 'this is my "quote"', "catch 'em all"]);
$csv[] = $arrayToCsvLine(["hello", 'this is my "quote"', "catch 'em all"]);
$csv[] = $arrayToCsvLine(["hello", 'this is my "quote"', "catch 'em all"]);

$csv = implode("\r\n", $csv);

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.

如果您收到错误只是因为您使用的是旧版本的 PHP。通过使用旧语法声明数组并用经典语法替换 lambda 函数来修复它。

回答by Aran

For those of you trying to sanitise data using PHP and output as a CSV this can be done using PHP's fputcsv() function without having to write to a file as such:

对于那些尝试使用 PHP 清理数据并输出为 CSV 的人来说,这可以使用 PHP 的 fputcsv() 函数来完成,而无需像这样写入文件:

<?php
// An example PHP array holding data to be put into CSV format
$data = [];
$data[] = ['row1_val1', 'row1_val2', 'row1_val3'];
$data[] = ['row2_val1', 'row2_val2', 'row2_val3'];

// Write to memory (unless buffer exceeds 2mb when it will write to /tmp)
$fp = fopen('php://temp', 'w+');
foreach ($data as $fields) {
    // Add row to CSV buffer
    fputcsv($fp, $fields);
}
rewind($fp); // Set the pointer back to the start
$csv_contents = stream_get_contents($fp); // Fetch the contents of our CSV
fclose($fp); // Close our pointer and free up memory and /tmp space

// Handle/Output your final sanitised CSV contents
echo $csv_contents;

回答by deceze

Don't store the data CSV escaped in the database. Escape it when you export to CSV using fputcsv. If you're storing it CSV escaped you're essentially storing garbage for all purposes other than CSV exporting.

不要将 CSV 转义的数据存储在数据库中。使用 .csv导出为 CSV 时将其fputcsv转义。如果您将其存储为 CSV 转义,则您实际上是在为 CSV 导出以外的所有目的存储垃圾。