類
<?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 = '';
/** 字段轉(zhuǎn)換的.回調(diào)函數(shù) @var null */
private $convert = null;
/** 直接下載@ var bool */
private $directDownload = true;
/** 腳本超時時間 @var int */
private $timeout = 300;
/**
* CSVExport constructor.
*
* @param $generator
* @param array $tableHeader 表頭,一維數(shù)組['field_name'=>'要展示的文字']
* @param string $fileName 下載時的文件名, 不含后綴
* @param callable $convert 回調(diào)函數(shù), 用來處理某些字段
*/
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;
}
/**
* 執(zhí)行查詢導(dǎo)出操作
*/
function doExport(){
set_time_limit($this->timeout);//超時限制
// 向?yàn)g覽器發(fā)送 http 下載頭
$this->sendHTTPHeader($this->fileName);
echo $this->tableHeaderDescImplode(); //表頭
//遍歷生成器, 發(fā)送數(shù)據(jù)
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;
}
/**
* 按照表頭字段,從結(jié)果集取出對應(yīng)的字段,拼接
* @param array $data 數(shù)據(jù)庫結(jié)果集, 一維數(shù)組
*
* @return string 拼接后的字符傳
*/
private function dataFieldImplode($data){
$str = '';
foreach ($this->tableHeaderFiledName as $field){
$str .= $data[$field]."\t,";
}
return rtrim($str,',').PHP_EOL;
}
/**
* 發(fā)送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");
}
}
調(diào)用
$query = "select * from skyshop_member limit 10000 ";
$generator = DB::connection()->cursor($query);
$tableHeader = [
'id'=>'序號',
'full_name'=>'全名'
];
$fileName = 'csv導(dǎo)出測試';
$callable = function($data){
if($data['id'] == 1){
$data['id'] = 'yi';
}
return $data;
};
$CSVExport = new CSVExport($generator, $tableHeader, $fileName,$callable);
$CSVExport->doExport();