在PHP中创建可下载的CSV文件
时间:2020-03-05 15:31:19 来源:igfitidea点击:
这个教程 解释了如何使用PHP创建CSV文件,以及如何下载文件而不是显示它。
<?php //Creates a new csv file and store it in tmp directory $new_csv = fopen('/tmp/report.csv', 'w'); fputcsv($new_csv, $row); fclose($new_csv); //output headers so that the file is downloaded rather than displayed header("Content-type: text/csv"); header("Content-disposition: attachment; filename = report.csv"); readfile("/tmp/report.csv"); ?>
这段代码告诉浏览器它正在生成一个CSV文件,应该提供给下载,而不是显示在浏览器中。
header("Content-type: text/csv");
内容的MIME类型是text/csv,csv文件的官方MIME类型。
header("Content-disposition: attachment; filename=report.csv");
标头提供建议的文件名并强制浏览器显示"保存"对话框。
readfile("/tmp/report.csv");
readfile-输出一个文件。