php 分片导出

$columns = [ 'id'=>'ID','name'=>'用户名称' ];
$data = [
        ['id'=>1,'name'=>'t1'],
        ['id'=>2,'name'=>'t2'],
        ['id'=>11,'name'=>'t11'],
        ['id'=>12,'name'=>'t12'],
        ['id'=>21,'name'=>'t21'],
        ['id'=>22,'name'=>'t22'],
    ];
$line = 10;
$times = ceil(count($data) / $line);

//准备导出excel
$fielName      = 'xxx.csv';
$excelCellName = array_values($columns);//excel需要返回的字段
$excelValue    = array_keys($columns);//DB对应的字段

header("Content-type: application/vnd.ms-excel; charset=UTF-8"); // 文件编码
header("Content-type: application/octet-stream");
header("Content-Disposition:attachment;filename = " . $fielName);

$fp = fopen('php://output', 'w');
fprintf($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));  // 设置编码的文件头
fputcsv($fp, array_values($excelCellName));

for ($i = 1; $i <= $times; $i++) {
    $zone_data = array_slice($data, ($i - 1) * $line, $line);
    foreach ($zone_data as $v) {
        $arr  = [];
        foreach ($excelValue as $k){
            if (isset($v[$k])) {
                $arr[] = $v[$k];
                continue;
            }
            $arr[] = 0;
        }
        fputcsv($fp, $arr);
        ob_flush();
        flush();
    }
}
fclose($fp);
exit();

考虑到数据量问题:可能会  >> 撑爆内存 or 输出超大流文件

解决方案:分页查询,分次输出

header("Content-type: application/vnd.ms-excel; charset=UTF-8"); // 文件编码
header("Content-type: application/octet-stream");
header("Content-Disposition:attachment;filename = " . $fielName);

$fp = fopen('php://output', 'w');
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));    // 设置编码的文件头
fputcsv($fp, array_values($excelCellName));
$excelValue = array_keys($excelCellName);//对应的字段
$id_range  = ['MAX(id) as max_id, MIN(id) as min_id'];   //结果id范围

$gameModel->setName('cash');//设置为用户表

$range = $gameModel->field($id_range)->find();   //查搜索结果的id范围

if (empty($range) || !$range['max_id'] || !$range['min_id']) {
fclose($fp);
exit();
}
$line = 10000;
$times = ceil(($range['max_id']-$range['min_id']+1) / $line);
$start = $range['min_id'];
$end = $range['min_id'] + $line;

for($i = 1; $i <= $times; $i++){
     $id_where = [];
     $id_where[] = ['id', '>=', $start];
     $id_where[] = ['id', '<', $end];
     $id_where = array_merge($where,$id_where);

     $data = $gameModel->getListData($alias, $id_where, $field, $join, $condition,0);

     foreach ($data as $k=> $v){
          $arr = [];foreach ($excelValue as $key){
               if (isset($v[$key])) {
                    $arr[] = $v[$key];
                    continue;
               }
          }
          fputcsv($fp, $arr);
          ob_flush();
          flush();
      }
      $start += $line;
      $end += $line;
}

fclose($fp);
exit();

 

posted @ 2021-04-29 14:23  羽*枫  阅读(206)  评论(0)    收藏  举报