<?php
set_time_limit(0);// 下载文件名
$filename = date('Y-m-d H:i:s', time());
//输出Excel文件头,可把user.csv换成你要的文件名
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
header('Cache-Control: max-age=0');$dsn = 'mysql:host=127.0.0.1;dbname=mysql';
$username = 'root';
$passwd = 'root';$dbh = new PDO($dsn, $username, $passwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec('set names utf8mb4');$res = $dbh->prepare("SELECT`mysql`.user.Host AS Host,`mysql`.user.User AS User,`mysql`.user.authentication_string AS authentication_string
FROM`mysql`.user"
);$res->execute();// 打开PHP文件句柄,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');// 计数器
$cnt = 0;
// 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
$limit = 100000;// 输出Excel列名信息
$head = array('Host', 'User');
foreach ($head as $i => $v) {// CSV的Excel支持GBK编码,一定要转换,否则乱码$head[$i] = iconv('utf-8', 'gb2312', $v);}fputcsv($fp, $head);// 逐行取出数据,不浪费内存
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {$cnt++;if ($limit == $cnt) { //刷新一下输出buffer,防止由于数据过多造成问题ob_flush();flush();$cnt = 0;}foreach ($row as $i => $v) {$row[$i] = iconv('utf-8', 'gb2312', $v);}fputcsv($fp, $row);
}