php百万数据导出csv方式

2022-10-11 21:01:31 117 0
魁首哥

set_time_limit(0);

php百万数据导出csv方式

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 = ‘lsf123456’;

$con = mysqli_connect($dbhost, $dbuser, $dbpwd);

if (mysqli_connect_errno()) {

die(‘connect error’);

}

//选择数据库

$database = ‘csdb’;

mysqli_select_db($con, $database);

//设置编码

mysqli_query($con, “set names UTF8”);

//我们试着用fputcsv从数据库中导出1百万的数据

//我们每次取1万条数据,分100步来执行

//如果线上环境无法支持一次性读取1万条数据,可把$nums调小,$step相应增大。

$step = 50;

$nums = 10000;

//设置标题

$title = array(‘编码’,’箱号连接’,’编码连接’);

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 sncode,xiangcode FROM `zx` LIMIT {$start},{$nums}”);

if($result) {

while($row = mysqli_fetch_assoc($result)) {

$row[‘xiangcode’]=’www.baidu.com?xx=’.$row[‘xiangcode’];

$row[‘lianjie’]=’www.baidu.com?lianjie=’.$row[‘sncode’];

foreach($row as $key => $item) {

//这里必须转码,不然会乱码

$row[$key] = iconv(“UTF-8”, “GBK”, $item);

}

fputcsv($fp, $row);

}

mysqli_free_result($result); //释放结果集资源

//每1万条数据就刷新缓冲区

ob_flush();

flush();

}

}

//断开连接

mysqli_close($con);

收藏
分享
海报
0 条评论
117
上一篇:干锅虾怎么做(干锅怎样做虾好吃又简单) 下一篇:皮肤热毒症状图片(湿毒是什么样子的图片)

本站已关闭游客评论,请登录或者注册后再评论吧~

忘记密码?

图形验证码