从数据库中导出数据到.csv文件

  考虑到csv文件比xls文件格式容易控制,所以在这次导出中用的是.csv格式。

  

  protected function exportInfo($arr, &$err){
$nameInfo = array('user_name'=>'vlson','age'=>'18','addrPrvoince'=>'北京');
$userInfo = $this->mysql->selectRows("select user_name, age, addr_province from user where addr_province like '%北京%');
$str = "名字,年龄,地区\n";
foreach($userInfo as $key=>$row){
$str .= $row['user_name'].",".$row['age'].",".$row['addr_province']."\n"; //用引文逗号分开,\n 可以让其换行
}
$filename = $nameInfo['addrPrvoince'].date('Y-m-d').'.csv'; //设置文件名
$this->export_csv($filename,$str); //导出
}
  private function export_csv($filename,$data) {
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');
echo $data;
exit();//输出之后退出或者die,否则会将代码写入到文件中
}
上一篇:Java线程及Jvm监控工具


下一篇:An exception occurred while acquiring a poolable resource. Will retry.