php导出数据csv
发表于:2024-07-24 16:46:30浏览:4224次
引言
php导出数据,文件名后缀为.csv
,该方法适合导出大数据
方法
if (!function_exists('export_csv_2')) {
/**
* 数据导出到excel(csv文件)
* @param array $fields,如:
* $fields = [
"user_id" => "所属人ID",
"user_name" => "用户名",
"take_time" => "收证日期",
"major_type" => "证书专业类型",
"take_amount" => "收证价格",
"dingjin_amount" => "预付定金",
"out_amount" => "挂证价格"
];
* @param array $dataArray
* @param $fileName
*/
function export_csv_2($fields = [], $dataArray = [], $fileName = '数据')
{
$in_key = array_keys($fields);
ini_set('memory_limit', '512M');
ini_set('max_execution_time', 0);
ob_end_clean();
ob_start();
header("Content-Type: text/csv");
header("Content-Disposition:filename=" . $fileName . date('YmdHis') . '.csv');
$fp = fopen('php://output', 'w');
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
fputcsv($fp, array_values($fields));
$index = 0;
foreach ($dataArray as $item) {
if ($index == 1000) {
$index = 0;
ob_flush();
flush();
}
$index++;
$new_item = [];
foreach ($item as $key => $value) {
if (in_array($key, $in_key)) {
$new_item[$key] = $value;
}
}
fputcsv($fp, $new_item);
}
ob_flush();
flush();
ob_end_clean();
}
}
栏目分类全部>