PHP csv大量数据导出分割处理

来源:互联网 发布:我国机电产品出口数据 编辑:程序博客网 时间:2024/06/06 02:01

后台管理系统总是成百万的数据导出,使用excel导出根本不能实现,excel只支持65536,2007和2010的是1048576,所以无论哪一种都不能满足需求,csv就符合需求,不限制记录的条数,但是大量数据如果一次性处理导出,会直接导致内存溢出,脚本停止工作,所有采用分割方式导出是比较有好处的。

<?php error_reporting(0);header ( "Content-type:application/vnd.ms-excel" );            header ( "Content-Disposition:filename=" . iconv ( "UTF-8", "GBK", "topic" ) . ".csv" );//连接数据库 $link = mysql_connect('localhost','root','root') or die('连接错误');//选择数据库mysql_select_db("bbs",$link);//设置字符集mysql_query("set names utf8");//查询函数function get_res($sql,$link){$res  = mysql_query($sql,$link);if(!$res){die("操作失败".mysql_error());}$arr=array();while ($row = mysql_fetch_assoc($res)) {                     $arr[]=$row;}return $arr;}//查询记录总数function getTotalCount(){$result = mysql_query("SELECT count(*) as count FROM medsci_edu_public_medsciedu_topic", $link);return $result['count'];}           // 打开PHP文件句柄,php://output 表示直接输出到浏览器            $fp = fopen('php://output', 'a');             //表头$column_name = array('topic_id','cat_id','user_id','is_best','is_top','topic_title',                 'topic_content','topic_img','hits','total_reply_count','created_time','last_updated_time','topic_status','last_reply_name');            // 将中文标题转换编码,否则乱码          foreach ($column_name as $i => $v) {                     $column_name[$i] = iconv('utf-8', 'gbk', $v);                }        // 将标题名称通过fputcsv写到文件句柄                fputcsv($fp, $column_name);          $pagecount = 10000;//一次读取多少条$totalcount = getTotalCount();//总记录数$sql = "select * from medsci_edu_public_medsciedu_topic";       for ($i=0;$i<intval($totalcount/$pagecount)+1;$i++){        $data = get_res($sql." limit ".strval($i*$pagecount).",{$pagecount}",$link);        foreach ( $data as $item ) {            $rows = array();            foreach ( $item as $v){                $rows[] = iconv('utf-8', 'GBK', $v);            }            fputcsv($fp, $rows);        }        // 将已经写到csv中的数据存储变量销毁,释放内存占用            unset($data);            //刷新缓冲区            ob_flush();            flush();    }    exit;
结果测试:

1 0