<?php
set_time_limit(0);
ini_set('memory_limit', '128M');
$fileName = date('YmdHis', time());
header('Content-Encoding: UTF-8');
header("Content-type:application/vnd.ms-excel;charset=UTF-8");
header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
$fp = fopen('php://output', 'a');
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpwd = '';
$con = mysqli_connect($dbhost, $dbuser, $dbpwd);
if (mysqli_connect_errno()) {
die('connect error');
}
$database = 'test';
mysqli_select_db($con, $database);
mysqli_query($con, "set names UTF8");
$step = 100;
$nums = 10000;
$where = "";
$title = array('ID','姓名‘,'年龄','性别');
foreach($title as $key => $item) {
$title[$key] =iconv("UTF-8", "GBK", $item);
}
fputcsv($fp, $title);
for($s = 1; $s <= $step; $s++) {
$start = ($s - 1) * $nums;
$result = mysqli_query($con,"SELECT * FROM `test` ".$where." ORDER BY `id` LIMIT {$start},{$nums}");
if($result) {
while($row = mysqli_fetch_assoc($result)) {
foreach($row as $key => $item) {
$row[$key] = iconv("UTF-8", "GBK", $item);
}
fputcsv($fp, $row);
}
mysqli_free_result($result);
ob_flush();
flush();
}
}
mysqli_close($con);