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头自动下载文件):
————————————————————————————