Home  >  Article  >  Backend Development  >  Detailed explanation of the method of exporting from database to .csv file in PHP

Detailed explanation of the method of exporting from database to .csv file in PHP

墨辰丷
墨辰丷Original
2018-05-19 15:15:411308browse

This article mainly introduces relevant information on the method of exporting from database to .csv file in PHP. Friends in need can refer to it

Method of exporting from database to .csv file in PHP

Implementation code:

public function export(){
 // 从数据库中获取数据,为了节省内存,不要把数据一次性读到内存,从句柄中一行一行读即可
 // 输出Excel文件头,可把user.csv换成你要的文件名
 header('Content-Type: application/vnd.ms-excel');
 header('Content-Disposition: attachment;filename="order.csv"');
 header('Cache-Control: max-age=0');
 $where=array(
   "paid"=>1,
   "pay_type"=>array("NEQ","offline"),
   "status"=>array("lt",3),
 );
 $stmt = M("Group_order")->field("order_id,order_name,num,price,total_money,contact_name,phone,zipcode,adress,wx_cheap,balance_pay,payment_money,tuan_type,pay_time,pay_type,third_id,is_mobile_pay,paid,status")->where($where)->order("order_id DESC")->limit(1000)->select();
   // 打开PHP文件句柄,php://output 表示直接输出到浏览器
 $fp = fopen('php://output', 'a');

 // 输出Excel列名信息
 $head = array("订单号","订单名称","购买数量","单价","总价","联系人姓名","联系人电话","邮编","详细地址","微信优惠金额","余额支付金额","真实支付金额","特卖类型(2为实物)","支付时间","支付类型","第三方支付id","是否是手机支付","是否支付","订单状态");
 foreach ($head as $i => $v) {
 // CSV的Excel支持GBK编码,一定要转换,否则乱码
   $head[$i] = iconv('utf-8', 'gbk', $v);
 }

 // 将数据通过fputcsv写到文件句柄
 fputcsv($fp, $head);

 // 计数器
 $cnt = 0;
 // 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
 $limit = 500;
 // 逐行取出数据,不浪费内存
 $count = count($stmt);
 for($t=0;$t<$count;$t++) {

 $cnt ++;
 if ($limit == $cnt) { //刷新一下输出buffer,防止由于数据过多造成问题
   ob_flush();
   flush();
   $cnt = 0;
 }
 $row = $stmt[$t];
foreach ($row as $i => $v) {
  if($i==&#39;pay_time&#39;){
     $v=date("Y-m-d,H:i:s",$v);
  }
   $row[$i] = iconv(&#39;utf-8&#39;, &#39;gbk&#39;, $v);
 }
 fputcsv($fp, $row);
 }
   fclose($fp);
 }

Related recommendations:

Detailed example of php generation.csv Method of suffix file table

Detailed example of exporting PHP from database to .csv file

Perfectly solves the problem of garbled characters when exporting data in excel’s .csv format from php

The above is the detailed content of Detailed explanation of the method of exporting from database to .csv file in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn