如何使fputcsv“回显”数据

时间:2011-01-14 15:32:03

标签: php csv export-to-csv

我需要一种方法让fputscv函数即时向浏览器写入数据,而不是创建临时文件,将数据保存到该文件中并执行echo file_get_contents()

4 个答案:

答案 0 :(得分:43)

在PHP文档网站上找到这个,首先在函数参考下发表评论:

function outputCSV($data) {
  $outstream = fopen("php://output", 'w');
  function __outputCSV(&$vals, $key, $filehandler) {
    fputcsv($filehandler, $vals, ';', '"');
  }
  array_walk($data, '__outputCSV', $outstream);
  fclose($outstream);
}

还有第二种选择:

$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);

希望这有帮助!

顺便说一句,在尝试解决问题时,PHP文档应始终是您的第一站。 : - )

答案 1 :(得分:16)

By a comment on the PHP site

<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>

答案 2 :(得分:2)

由于原始提问者想要“即时写入浏览器”,如果你想强制一个文件名和一个要求下载文件的对话框,也许值得注意(就像我的情况一样,没有人提到它)在浏览器中,您必须在输出fputcsv之前设置正确的标题:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=myFile.csv');

答案 3 :(得分:0)

实际上,制作CSV并不是那么困难(解析CSV涉及更多一点)。

用于将2D数组编写为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";
}