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

有帮助吗?

解决方案

在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文档在试图解决问题时始终是您的第一站。 :-)

其他提示

通过PHP网站上的评论

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

正如原始的Asker想要“随时写给浏览器”,也许值得注意(就像我的情况一样,没有人提到),如果您想强制文件名和对话框,要求在浏览器中下载文件,您必须在输出任何内容之前设置适当的标头 fputcsv:

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

实际上,生产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";
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top