php - 從數據庫導出百萬級數據(CSV文件)

將數據庫鏈接信息、查詢條件、標題信息替換爲真實數據便可使用。php

 1 <?php
 2 set_time_limit(0);
 3 ini_set('memory_limit', '128M');
 4  
 5 $fileName = date('YmdHis', time());
 6 header('Content-Encoding: UTF-8');
 7 header("Content-type:application/vnd.ms-excel;charset=UTF-8");
 8 header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
 9  
10  
11 //打開php標準輸出流
12 //以寫入追加的方式打開
13 $fp = fopen('php://output', 'a');
14 
15 //鏈接數據庫
16 $dbhost = '127.0.0.1';
17 $dbuser = 'root';
18 $dbpwd = '';
19 $con = mysqli_connect($dbhost, $dbuser, $dbpwd);
20 if (mysqli_connect_errno()) {
21    die('connect error');
22 }
23 //選擇數據庫
24 $database = 'test';
25 mysqli_select_db($con, $database);
26 //設置編碼
27 mysqli_query($con, "set names UTF8");
28 
29  
30 //咱們試着用fputcsv從數據庫中導出1百萬的數據
31 //咱們每次取1萬條數據,分100步來執行
32 //若是線上環境沒法支持一次性讀取1萬條數據,可把$nums調小,$step相應增大。
33 $step = 100;
34 $nums = 10000;
35 $where = ""; //篩選條件
36  
37 //設置標題
38 $title = array('ID','姓名','年齡','性別');
39 foreach($title as $key => $item) {
40     $title[$key] =iconv("UTF-8", "GBK", $item);
41 }
42 //將標題寫到標準輸出中
43 fputcsv($fp, $title);
44 
45 for($s = 1; $s <= $step; $s++) {
46     $start = ($s - 1) * $nums;
47     $result = mysqli_query($con,"SELECT * FROM `test` ".$where." ORDER BY `id` LIMIT {$start},{$nums}");
48     if($result) {
49         while($row = mysqli_fetch_assoc($result)) {
50             foreach($row as $key => $item) {
51                 //這裏必須轉碼,否則會亂碼
52                 $row[$key] = iconv("UTF-8", "GBK", $item);
53             }
54             fputcsv($fp, $row);
55         }
56         mysqli_free_result($result); //釋放結果集資源
57 
58         //每1萬條數據就刷新緩衝區
59         ob_flush();
60         flush();
61     }
62 }
63 //斷開鏈接
64 mysqli_close($con);
相關文章
相關標籤/搜索