php导出csv文件格式比起用PHPExcel插件导出excel文件速度快100倍!
以下是几种不同的PHP导出CSV文件的方法:
方法一(php://output方式用fputcsv函数格式化成csv数据):
------------------------------------------------------------------------------------
$data = array(
array("Name", "Age", "Email"),
array("John Doe", 25, "johndoe@example.com"),
array("Jane Smith", 30, "janesmith@example.com"),
);
$filename = "data.csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=' . $filename);
$output = fopen('php://output', 'w');
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
exit;
方法二(application/octet-stream读取文件数据流):
------------------------------------------------------------------------------------
$data = array(
array("Name", "Age", "Email"),
array("John Doe", 25, "johndoe@example.com"),
array("Jane Smith", 30, "janesmith@example.com"),
);
$filename = "data.csv";
$output = fopen($filename, 'w');
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
// 下载文件
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filename));
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
方法三(设置Header头自动下载文件):
------------------------------------------------------------------------------------
$data = array(
array("Name", "Age", "Email"),
array("John Doe", 25, "johndoe@example.com"),
array("Jane Smith", 30, "janesmith@example.com"),
);
$filename = "data.csv";
$output = fopen($filename, 'w');
foreach ($data as $row) {
$rowString = implode(',', $row) . "\n";
fwrite($output, $rowString);
}
fclose($output);
// 下载文件
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filename));
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
这些方法都是将数据数组写入到CSV文件中,并通过适当的头部设置强制浏览器下载生成的CSV文件。
在第一种方法中,我们使用了php://output来直接将CSV数据发送到浏览器。
第二种和第三种方法将CSV文件保存到服务器上,然后通过读取和输出文件内容来提供下载。
本人喜欢第三种方法导出CSV,你们呢?