PHP导出csv文件格式(最快捷的方式导出Excel文件)

1 篇文章 0 订阅
1 篇文章 0 订阅

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,你们呢? 


 

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值