类
<?php
namespace App\Libs;
class CSVExport
{
/** @var null 查询 MYSQL得到的生成器 */
private $generator = null;
/** @var array 表头 */
private $tableHeader = array();
/** 表头中的字段名 @var array */
private $tableHeaderFiledName = array();
/** 表头中的输出显示汉字 @var array */
private $tableHeaderFiledNameDesc = array();
/** 下载的文件名,不带后缀 @var string */
private $fileName = '';
/** 字段转换的.回调函数 @var null */
private $convert = null;
/** 直接下载@ var bool */
private $directDownload = true;
/** 脚本超时时间 @var int */
private $timeout = 300;
/**
* CSVExport constructor.
*
* @param $generator
* @param array $tableHeader 表头,一维数组['field_name'=>'要展示的文字']
* @param string $fileName 下载时的文件名, 不含后缀
* @param callable $convert 回调函数, 用来处理某些字段
*/
public function __construct ($generator, $tableHeader , $fileName = '' , $convert = null)
{
$this->generator = $generator;
$this->tableHeader = $tableHeader;
$this->tableHeaderFiledName = array_keys($tableHeader);
$this->tableHeaderFiledNameDesc = array_values($tableHeader);
$this->fileName = $fileName ? $fileName : md5(time());
$this->convert = $convert;
}
/**
* @return float|int
*/
public function getTimeout ()
{
return $this->timeout;
}
/**
* @param float|int $timeout
*/
public function setTimeout ($timeout)
{
$this->timeout = $timeout;
}
/**
* 执行查询导出操作
*/
function doExport(){
set_time_limit($this->timeout);//超时限制
// 向浏览器发送 http 下载头
$this->sendHTTPHeader($this->fileName);
echo $this->tableHeaderDescImplode(); //表头
//遍历生成器, 发送数据
foreach ($this->generator as $data) {
$data = get_object_vars($data);
if ($this->convert){
$data = call_user_func($this->convert,$data);
}
echo $this->dataFieldImplode($data);
}
}
/**
* 拼接表头
* @return string 逗号分割的表头字符串
*/
private function tableHeaderDescImplode(){
$str = implode("\t,", $this->tableHeaderFiledNameDesc);
return $str.PHP_EOL;
}
/**
* 按照表头字段,从结果集取出对应的字段,拼接
* @param array $data 数据库结果集, 一维数组
*
* @return string 拼接后的字符传
*/
private function dataFieldImplode($data){
$str = '';
foreach ($this->tableHeaderFiledName as $field){
$str .= $data[$field]."\t,";
}
return rtrim($str,',').PHP_EOL;
}
/**
* 发送http下载header
*
* @param $fileName
*/
private function sendHTTPHeader($fileName){
header("Cache-control: private");
header("Pragma: public");
header('Content-type: application/x-csv');
header("Content-Disposition:attachment;filename=" . $fileName. ".csv");
}
}
调用
$query = "select * from skyshop_member limit 10000 ";
$generator = DB::connection()->cursor($query);
$tableHeader = [
'id'=>'序号',
'full_name'=>'全名'
];
$fileName = 'csv导出测试';
$callable = function($data){
if($data['id'] == 1){
$data['id'] = 'yi';
}
return $data;
};
$CSVExport = new CSVExport($generator, $tableHeader, $fileName,$callable);
$CSVExport->doExport();