php 如何使 fputcsv“回显”数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4692709/
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
How to make fputcsv "echo" the data
提问by Salman A
回答by Seb Barre
Found this on the PHP docs website, first comment under the function reference:
在PHP docs网站上找到了这个,在函数参考下先评论:
function outputCSV($data) {
$outstream = fopen("php://output", 'w');
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ';', '"');
}
array_walk($data, '__outputCSV', $outstream);
fclose($outstream);
}
And a second option:
还有第二个选择:
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
fputcsv($csv, array('blah','blah'));
rewind($csv);
// put it all in a variable
$output = stream_get_contents($csv);
Hope this helps!
希望这可以帮助!
BTW the PHP docs should always be your first stop when trying to figure things out. :-)
顺便说一句,PHP 文档应该始终是您尝试解决问题时的第一站。:-)
回答by powtac
<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>
回答by Pere
As the original asker wanted to "write to the browser on the fly", maybe is worth noting (as was my case and noone mentioned it) that if you want to force a file name and a dialog asking to download a file in the browser, you must set the proper headers before outputting anything with fputcsv
:
由于最初的提问者想要“即时写入浏览器”,因此可能值得注意(就像我的情况一样,没有人提到过),如果您想强制使用文件名和对话框要求在浏览器中下载文件,您必须在输出任何内容之前设置正确的标题fputcsv
:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=myFile.csv');
回答by Lee Kowalkowski
Producing a CSV is actually not all that difficult (parsing a CSV is a little bit more involved).
生成 CSV 实际上并不是那么困难(解析 CSV 有点复杂)。
Sample code for writing a 2D Array as CSV:
将二维数组写入 CSV 的示例代码:
$array = [
[1,2,3],
[4,5,6],
[7,8,9]
];
// If this CSV is a HTTP response you will need to set the right content type
header("Content-Type: text/csv");
// If you need to force download or set a filename (you can also do this with
// the download attribute in HTML5 instead)
header('Content-Disposition: attachment; filename="example.csv"')
// Column heading row, if required.
echo "Column heading 1,Column heading 2,Column heading 3\n";
foreach ($array as $row) {
$row = array_map(function($cell) {
// Cells containing a quote, a comma or a new line will need to be
// contained in double quotes.
if (preg_match('/["\n,]/', $cell)) {
// double quotes within cells need to be escaped.
return '"' . preg_replace('/"/', '""', $cell) . '"';
}
return $cell;
}, $row);
echo implode(',', $row) . "\n";
}