php 强制 fputcsv 对 *all* 字段使用 Enclosure
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2489553/
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
Forcing fputcsv to Use Enclosure For *all* Fields
提问by Alan Storm
When I use fputcsvto write out a line to an open file handle, PHP will add an enclosing character to any column that it believes needs it, but will leave other columns without the enclosures.
当我使用fputcsv向打开的文件句柄写出一行时,PHP 会向它认为需要它的任何列添加一个封闭字符,但会保留其他没有封闭字符的列。
For example, you might end up with a line like this
例如,你可能会得到这样的一行
11,"Bob ",Jenkins,"200 main st. USA ",etc
Short of appending a bogus space to the end of every field, is there any way to force fputcsv to always enclose columns with the enclosure (defaults to a ") character?
除了在每个字段的末尾附加一个虚假空格之外,有没有办法强制 fputcsv 始终用外壳(默认为“)字符将列括起来?
采纳答案by VolkerK
No, fputcsv() only encloses the field under the following conditions
否,fputcsv() 仅在以下条件下封闭该字段
/* enclose a field that contains a delimiter, an enclosure character, or a newline */
if (FPUTCSV_FLD_CHK(delimiter) ||
FPUTCSV_FLD_CHK(enclosure) ||
FPUTCSV_FLD_CHK(escape_char) ||
FPUTCSV_FLD_CHK('\n') ||
FPUTCSV_FLD_CHK('\r') ||
FPUTCSV_FLD_CHK('\t') ||
FPUTCSV_FLD_CHK(' ')
)
There is no "always enclose" option.
没有“始终附上”选项。
回答by Diego Sebastian Mera
Not happy with this solution but it is what I did and worked. The idea is to set an empty char as enclosure character on fputcsv and add some quotes on every element of your array.
对这个解决方案不满意,但这是我所做和工作的。这个想法是在 fputcsv 上将一个空字符设置为封闭字符,并在数组的每个元素上添加一些引号。
function encodeFunc($value) {
return "\"$value\"";
}
fputcsv($handler, array_map(encodeFunc, $array), ',', chr(0));
回答by dearsina
Building on Martin's answer, if you want to avoid inserting any characters that don't stem from the source array (Chr(127), Chr(0), etc), you can replace the fputcsv() line with the following instead:
建立在马丁的回答,如果你想避免将不从源阵列(干任何字符Chr(127),Chr(0)等等),你可以替换,而不是下面的fputcsv()行:
fputs($fp, implode(",", array_map("encodeFunc", $row))."\r\n");
Granted, fputs() is slower than fputcsv(), but it's a cleaner output. The complete code is thus:
诚然,fputs() 比 fputcsv() 慢,但它是一个更清晰的输出。完整的代码是这样的:
/***
* @param $value array
* @return string array values enclosed in quotes every time.
*/
function encodeFunc($value) {
///remove any ESCAPED double quotes within string.
$value = str_replace('\"','"',$value);
//then force escape these same double quotes And Any UNESCAPED Ones.
$value = str_replace('"','\"',$value);
//force wrap value in quotes and return
return '"'.$value.'"';
}
$fp = fopen("filename.csv", 'w');
foreach($table as $row){
fputs($fp, implode(",", array_map("encodeFunc", $row))."\r\n");
}
fclose($fp);
回答by Martin
After a lot of scrafffing around and some somewhat tedious character checking, I have a version of the above referenced codes by Diegoand Mahnthat will correctly strip out encasings and replace with double quotes on all fields in fputcsv. and then output the file to the browser to download.
经过大量的乱七八糟和一些有些乏味的字符检查之后,我得到了上面由Diego和Mahn引用的代码的一个版本,它可以正确地去除封装并在fputcsv. 然后将文件输出到浏览器进行下载。
I also had a secondary issue of not being able to be sure that double quotes were always / never escaped.
我还有一个次要问题,即无法确定双引号总是/从不转义。
Specifically for when outputting directly to browser using the php://input stream as referenced by Diego. Chr(127)is a space character so the CSV file has a few more spaces than otherwise but I believe this sidesteps the issue of chr(0)NULL characters in UTF-8.
专门用于使用 Diego 引用的 php://input 流直接输出到浏览器时。Chr(127)是一个空格字符,所以 CSV 文件比其他文件有更多的空格,但我相信这回避了chr(0)UTF-8中NULL 字符的问题。
/***
* @param $value array
* @return string array values enclosed in quotes every time.
*/
function encodeFunc($value) {
///remove any ESCAPED double quotes within string.
$value = str_replace('\"','"',$value);
//then force escape these same double quotes And Any UNESCAPED Ones.
$value = str_replace('"','\"',$value);
//force wrap value in quotes and return
return '"'.$value.'"';
}
$result = $array_Set_Of_DataBase_Results;
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export-'.date("d-m-Y").'.csv"');
foreach($result as $row) {
fputcsv($fp, array_map("encodeFunc", $row), ',', chr(127));
}
unset($result,$row);
die;
}
I hope this is useful for some one.
我希望这对某些人有用。

