fputcsv() 是一个很棒的小函数,所以我不会放弃它。
相反,我建议您使用 PHP 的内置I/O Wrappers
例如,您可以这样做以逐行“流式传输”您的 CSV 数据(取决于各种输出缓冲区,但这是另一回事):
<?php
header('Content-type: text/csv; charset=UTF-8');
header('Content-disposition: attachment; filename=report.csv');
$fp = fopen('php://output','w');
foreach($arrays as $array) fputcsv($fp, $array);
这很好用,但如果出现问题,您的用户将无法下载。
因此,如果您没有太多数据,您可以只写入内存中的流,只需交换php://output
并php://memory
移动内容:
<?php
$fp = fopen('php://memory','rw');
// our generateData() function might throw an exception, in which case
// we want to fail gracefully, not send the user a broken/incomplete csv.
try {
while($row = generateData()) fputcsv($fp, $row);
}catch(\Exception $e){
// display a nice page to your user and exit/return
}
// SUCCESS! - so now we have CSV data in memory. Almost like we'd spooled it to a file
// on disk, but we didn't touch the disk.
//rewind our file handle
rewind($fp);
//send output
header('Content-type: text/csv; charset=UTF-8');
header('Content-disposition: attachment; filename=report.csv');
stream_get_contents($fp);