php - 从数据库导出百万级数据(CSV文件)

将数据库连接信息、查询条件、标题信息替换为真实数据即可使用。

 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);

 

转载于:https://www.cnblogs.com/whx-blogs/p/9973482.html

你可能感兴趣的:(数据库,php,大数据)