php如何导出csv文件(代码示例)

<?php
$data = [
  ['id'=>1,'name'=>'陈大大','create_time'=>'2019-11-12'],
  ['id'=>2,'name'=>'陈中中','create_time'=>'2019-11-13'],
];
$headerArray = ['序号','用户名','注册时间'];
$string = implode(",",$headerArray)."\n";//先做出表头
foreach ($data as $key => $value) {
  //把需要的字段一一对应起来,如果已经对应好 直接 $outArray = $value;
  $outArray['id'] = $value['id'];
  $outArray['name'] = $value['name'];
  $outArray['create_time'] = $value['create_time'];
  $string .= implode(",",$outArray)."\n"; //用英文逗号分开 
}
$filename = date('Ymd').'.csv'; //设置文件名
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
exit(mb_convert_encoding($string, "GBK", "UTF-8"));

转于:https://www.jianshu.com/p/4683280832f6

posted @ 2019-11-21 18:03  张志健  阅读(358)  评论(0编辑  收藏  举报