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

WBOY
Release: 2016-06-23 13:29:57
Original
2303 people have browsed it

后台管理系统总是成百万的数据导出,使用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 get_res limit foreach as array iconv fputcsv unset ob_flush flush exit>结果测试:    <br>  <br>  <p></p>  <p class="sycode">   </p>
<p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>   </intval>
Copy after login
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template