/**
* 导出Csv
*
* @param array $headers 标题行,| 后面表示默认值,如:['id' => 'ID|0' , 'name' => '姓名|/' , 'age' => '年龄|0']
* @param array $data 数据
* 如:[['id' => 1 , 'name' => '张三','age'=>18] , ['id' => 2 , 'name' => '张三','age' => 18]]
* @param string $filename 文件名
* @param mixed number | string $default 字段默认值
* @param mixed $handle resource | string | null 文件资源,默认取PHP标准输出流,以可以指定文件名
* @param bool $closedHandle 是否关闭文件流 用于数据分页查询导出
*
* @return mixed resource | bool
* @throws UnexpectedValueException
* @author jp Email:505465482@qq.com
*/
public function exportCsvSuper(array $headers, array $data, string $filename = 'igvault', $default = '/', $handle = null, bool $closedHandle = true)
{
if (empty($headers) || empty($data)) {
throw new UnexpectedValueException('标题或行数据不能为空');
}
if (count($headers) != count(current($data))) {
//throw new UnexpectedValueException('标题数和行数不匹配');
}
//检测是否是文件句柄
if (is_resource($handle)) {
$handle = $handle;
} else {
print(chr(0xEF) . chr(0xBB) . chr(0xBF));//防止特殊字符乱码
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename={$filename}.csv");
header('Cache-Control: max-age=0');
self::setPHPWithoutLimit();
if (is_null($handle)) {
$handle = fopen('php://output', 'a');
} else {
if (!file_exists($handle)) {
touch($handle);
}
$handle = fopen($handle, 'a');
}
//放入标题
$heads = array_values($headers);
fputcsv($handle, $heads);
}
//获取所有要进 CSV 文件的字段
$columns = array_keys($headers);
//放入数据
foreach ($data as $item) {
if (empty($item)) continue;
//检测ID等字段存在性,不存在 /
$arr = [];
foreach ($columns as $column) {
if (strrpos($headers[$column], '|') !== false) {
$temp = explode('|', $headers[$column]);
$default = end($temp);
}
$arr[] = $item[$column] ?? $default;
}
fputcsv($handle, $arr);
}
//传说可以刷新暂存区数据
ob_flush();
flush();
if ($closedHandle) {
fclose($handle);
} else {
return $handle;
}
}