我目前正在创建和输出CSV,如下所示:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file.csv');
header("Cache-Control: no-store, no-cache");
$df = fopen('php://output', 'w');
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($csvLines as $csvLine) {
fputcsv($df, $csvLine);
}
exit;
但是,我不仅要输出,还要将此文件保存到磁盘。如何将$df
写入文件?
注意欢迎提出改进生成CSV的建议:)
答案 0 :(得分:1)
最简单的答案是写入文件而不是php://output
,然后使用readfile()
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file.csv');
header("Cache-Control: no-store, no-cache");
$df = fopen('/path/to/where/you/want/the/file/on/disk.csv', 'w');
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($csvLines as $csvLine) {
fputcsv($df, $csvLine);
}
readfile('/path/to/where/you/want/the/file/on/disk.csv');
exit;
答案 1 :(得分:0)
只需写入两个文件指针:
$out = fopen('php://output', 'w');
$file = fopen('somefile.csv');
fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($csvLines as $csvLine) {
fputcsv($out, $csvLine);
fputcsv($file, $csvLine);
}
exit;