PHP 实现从数据库导出到.csv文件方法
实现代码:
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=='pay_time'){
$v=date("Y-m-d,H:i:s",$v);
}
$row[$i] = iconv('utf-8',$v);
}
fputcsv($fp,$row);
}
fclose($fp);
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:https://www.f2er.com/php/17179.html