1. 程式人生 > 其它 >匯出csv檔案_php匯出超大csv檔案(匯出資料量建議大於1萬)

匯出csv檔案_php匯出超大csv檔案(匯出資料量建議大於1萬)

技術標籤:匯出csv檔案

7be8b6114bf65131e61a0e5551ad8291.png
//資料量在1萬以下的建議使用phpexcel匯出//控制器裡面的方法static function getData($total_page=1, $page_nums=10000) {  for($i=0; $i ({$i}*{$page_nums}) LIMIT {$page_nums}"; $start = $i * $page_nums; $sql = "SELECT * FROM xcx_members LIMIT {$start},{$page_nums}"; //$sql2="SELECT a.*, (select mobile from xcx_members b where b.id=a.parent_id) as tjr_mobile FROM xcx_members a where id>=(select id from xcx_members where v_type=1 order by id asc limit {$start},1) limit {$page_nums}"; //此處members表需要組合索引 create index v_type_id_index on members(v_type,id); //欄位v_type tinyint default 0 $list = Db::query($sql) foreach($list as $k=>$v) { yield [$v['mobile'],$v['realname'],$v['nickname'],$v['avatar']]; }  unset($list); //每1萬條資料就重新整理緩衝區 ob_flush(); flush(); //sleep(1); } }  public function index() { //生成的csv檔名稱 $demo_csv_filename = time().".csv";  //每頁查詢數量 $page_nums = 10000;  //總頁數 $count = Db::name("members")->count("id"); if($count < $page_nums) { $total_page = 1; } else { $total_page = intval($count / $page_nums) + 1;  } //csv檔案存入的路徑 $base_path = CMF_ROOT."public/upload/";  //匯入表頭 $title = [ '手機號','真實姓名','暱稱','頭像' ];  $fp = fopen($base_path.$demo_csv_filename, 'w');  //寫入標題 fputcsv($fp, $title);  fclose($fp);  $fp = fopen($base_path.$demo_csv_filename, 'a');  foreach(self::getData($total_page, $page_nums) as $m=>$n) { //寫入內容 fputcsv($fp, $n); }  fclose($fp);  $download_url = cmf_get_domain()."/upload/".$demo_csv_filename;  echo "";  die; }