<?php |
02 |
//
输出Excel文件头,可把user.csv换成你要的文件名 |
03 |
header( 'Content-Type:
application/vnd.ms-excel' ); |
04 |
header( 'Content-Disposition:
attachment;filename="user.csv"' ); |
05 |
header( 'Cache-Control:
max-age=0' ); |
06 |
|
07 |
//
从数据库中获取数据,为了节省内存,不要把数据一次性读到内存,从句柄中一行一行读即可 |
08 |
$sql = 'select
* from tbl where ……' ; |
09 |
$stmt =
mysql_ query( $sql ); |
10 |
|
11 |
//
打开PHP文件句柄,php://output 表示直接输出到浏览器 |
12 |
$fp = fopen ( 'php://output' , 'a' ); |
13 |
|
14 |
//
输出Excel列名信息 |
15 |
$head = array ( '姓名' , '性别' , '年龄' , 'Email' , '电话' , '……' ); |
16 |
foreach ( $head as $i => $v )
{ |
17 |
//
CSV的Excel支持GBK编码,一定要转换,否则乱码 |
18 |
$head [ $i ]
= iconv( 'utf-8' , 'gbk' , $v ); |
19 |
} |
20 |
|
21 |
//
将数据通过fputcsv写到文件句柄 |
22 |
fputcsv ( $fp , $head ); |
23 |
|
24 |
//
计数器 |
25 |
$cnt =
0; |
26 |
//
每隔$limit行,刷新一下输出buffer,不要太大,也不要太小 |
27 |
$limit =
100000; |
28 |
|
29 |
//
逐行取出数据,不浪费内存 |
30 |
while ( $row =
mysql_fetch_array( $stmt,MYSQL_ASSOC) )
{ |
31 |
|
32 |
$cnt ++; |
33 |
if ( $limit == $cnt )
{ //刷新一下输出buffer,防止由于数据过多造成问题 |
34 |
ob_flush(); |
35 |
flush (); |
36 |
$cnt =
0; |
37 |
} |
38 |
|
39 |
foreach ( $row as $i => $v )
{ |
40 |
$row [ $i ]
= iconv( 'utf-8' , 'gbk' , $v ); |
41 |
} |
42 |
fputcsv ( $fp , $row ); |
43 |
}
|