php导出数据到csv文件

$count = M('revieworder')->where($map)->count();
set_time_limit(0);
ini_set('memory_limit', '256M');
$filename = '预约' . time() . '.csv';
header("Content-type:text/csv");
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
// 打开PHP文件句柄,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');
$head = array('编号','姓名','手机号','预约日期','***','区域','短信发送','备注','申请时间');
foreach ($head as $i => $v) {
// CSV的Excel支持GBK编码,一定要转换,否则乱码
$head[$i] = iconv('utf-8', 'gbk', $v);
}
// 将数据通过fputcsv写到文件句柄
fputcsv($fp, $head);
// 从数据库中获取数据,为了节省内存,不要把数据一次性读到内存,从句柄中一行一行读即可
$limit = 10000;
for ($i = 0; $i < $count; $i = $i + $limit) {
$list = M('revieworder')->where($map)->order('createtime desc')->limit($i, $limit)->select();
foreach ($list as $k => $val) {
$rows[0] = iconv('utf-8', 'gbk', $k + 1);
$rows[1] = iconv('utf-8', 'gbk', "\t" . $val['realname']);
$rows[2] = iconv('utf-8', 'gbk', $val['mobile']);
$rows[3] = iconv('utf-8', 'gbk', "\t" . getSubstr($val['orderdate'],0,10).' '.$val['amorpm']);
$rows[4] = iconv('utf-8', 'gbk', $val['subject']);
$rows[5] = iconv('utf-8', 'gbk', $val['area']);
$rows[6] = iconv('utf-8', 'gbk', $val['issend'] == '1'?'已发送':'未发送');
$rows[7] = iconv('utf-8', 'gbk', $val['note']);
$rows[8] = iconv('utf-8', 'gbk', time_format($val['createtime']));
fputcsv($fp, $rows);
unset($rows);
}
ob_flush();
flush(); //刷新buffer
}
exit;
posted @ 2017-06-29 15:10  (BACH)  阅读(397)  评论(0编辑  收藏  举报