set_time_limit(0);
ini_set ('memory_limit', '256M');
$db = $this->load->database('default',true);
$sql = "SELECT * FROM `t_mobile_number_section` $condition";
$query = $db->query($sql);
$result = $query->result_array();
$filename = 'number'.time().'.csv';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
// 打开PHP文件句柄,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');
// 输出Excel列名信息
$head = array($title['number_section'],$title['area_code'],$title['province'],$title['city']);
foreach ($head as $i => $v) {
// CSV的Excel支持GBK编码,一定要转换,否则乱码
$head[$i] = iconv('utf-8', 'gbk', $v);
}
// 将数据通过fputcsv写到文件句柄
fputcsv($fp, $head);
// 计数器
$cnt = 0;
$limit = 100000;
// 从数据库中获取数据,为了节省内存,不要把数据一次性读到内存,从句柄中一行一行读即可
$i = 2;
$count = 0;
foreach ($result as $key => $val) {
$count ++;
$cnt ++;
//每隔$limit行,刷新一下输出buffer,不要太大,也不要太小 ,大数据量时处理
if ($limit == $cnt) { //刷新一下输出buffer,防止由于数据过多造成问题
ob_flush();
flush(); //刷新buffer
$cnt = 0;
}
$rows[$i] = iconv('utf-8', 'gbk', $val['number_section']);
$rows[$i+1] = iconv('utf-8', 'gbk', $val['area_code']);
$rows[$i+2] = iconv('utf-8', 'gbk', $val['province']);
$rows[$i+3] = iconv('utf-8', 'gbk', $val['city']);
fputcsv($fp, $rows);
}