php利用fputcsv导出大数据

使用原生的fputcsv导出数据,性能更好

导出的数据格式:

Array
(
    [0] => Array
        (
            [0] => id          
            [2] => send_status
            [3] => created_at
            [4] => level
            [5] => price
            [6] => phone
        )

    [1] => Array
        (
            [id] => 8            
            [send_status] => 未发奖
            [created_at] => 2019-03-06 02:54:31
            [level] => 一等奖
            [price] => 0.00
            [phone] => 
        )

    [2] => Array
        (
            [id] => 9
            [token] => o_l54wLlCrhDVbS6tRZD5kDYOS5E
            [send_status] => 未发奖
            [created_at] => 2019-03-06 02:55:04
            [level] => 二等奖
            [price] => 50.00
            [phone] => 
        )

)

方法函数:

/**
 * 处理Excel导出
 * @param $filename
 * @param $data
 */
public function doExcel($filename, $data)
{
   header('Content-Type: application/vnd.ms-execl');
   header('Content-Disposition: attachment;filename="' . $filename . '.csv"');

   //以写入追加的方式打开
   $fp = fopen('php://output', 'a');

   $i = 0;
   if ($data) {
      foreach ($data as $k => $v) {
         // CSV的Excel支持GBK编码,一定要转换,否则乱码
         foreach ($v as $k2 => $v2) {
            $v[$k2] = iconv("utf-8", "GBK", $v2);
         }
         fputcsv($fp, $v);
         $i++;
         if ($i > 20000) {//读取一部分数据刷新下输出buffer
            ob_flush();
            flush();
            $i = 0;
         }
      }
   }

   fclose($fp);
}

爱生活,爱技术

You may also like...

发表评论

电子邮件地址不会被公开。 必填项已用*标注