php导出23万条数据,thinkphp3.2导出百万条数据的方法【原创】

namespace Mobile\Controller;

use Think\Controller;

class DemoController extends Controller {

public function index(){

$this->display();

}

public function explode_cvs(){

$count = M('Users')->field('user_id,account,user_name')->count();

$num = 10000;

$page = new \Common\Util\CPage($count,$num);

$list = M('Users')->field('user_id,account,user_name')->order("user_id asc")->limit("{$page->firstRow},{$page->listRows}")->select();

$next = $page->show();

$titleList = array('user_id', '用户名', '姓名');

$file = "./00000.csv";

$res = $this->set_title($titleList,$file);

if($res) {

$result = $this->csv_export($list,$titleList,$file);

if($result) {

$j = array('status'=>1,'next'=>$next['next'],'bar'=>round($next['page']/$next['total']*100,2),'total'=>$next['total'],'p'=>$next['p'],'file'=>$file,'backurl'=>U('Mobile/Index/index'));

echo json_encode($j);exit;

} else {

echo 1;

}

}

}

private function set_title($titleList,$file){

$csvData = '';

$nums = count($titleList);

for ($i = 0; $i < $nums - 1; $i++)

{

$csvData .= '"' . $titleList[$i] . '",';

}

$csvData .= '"' . $titleList[$nums - 1] . "\"\r\n";

$csvData = mb_convert_encoding($csvData, "cp936", "UTF-8");

if(!file_exists($file)) {

file_put_contents($file,$csvData);

}

return true;

}

private function csv_export(&$data,$titleList,$fileName = '')

{

ini_set("max_execution_time", "3600");

$csvData = '';

$nums = count($titleList);

foreach ($data as $key => $row)

{

$i = 0;

foreach ($row as $_key => $_val)

{

$_val = str_replace("\"", "\"\"", $_val);

if ($i < ($nums - 1))

{

$csvData .= '"' . $_val . '",';

}

elseif ($i == ($nums - 1))

{

$csvData .= '"' . $_val . "\"\r\n";

}

$i++;

}

unset($data[$key]);

}

$csvData = mb_convert_encoding($csvData, "cp936", "UTF-8");

file_put_contents($fileName,$csvData,FILE_APPEND);

return true;

}

public function download($file){

if (file_exists($file)) {

header('Content-Description: File Transfer');

header("Content-type:text/csv;");

header('Content-Disposition: attachment; filename='.basename($file));

header('Content-Transfer-Encoding: binary');

header('Expires: 0');

header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

header('Pragma: public');

header('Content-Length: ' . filesize($file));

ob_clean();

flush();

readfile($file);

@unlink($file);

exit;

}

}

}

转载请注明出处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值