您的当前位置:首页>全部文章>文章详情

php导出数据csv

发表于:2024-07-24 16:46:30浏览:4332次TAG: #PHP #导出 #csv

引言

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 = '数据')
    {
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);

        // 输出CSV文件头
        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)); // UTF-8 BOM防止中文乱码
        fputcsv($fp, array_values($fields));

        // 逐行输出数据
        $index = 0;
        foreach ($dataArray as $item) {
            if ($index === 1000) {
                $index = 0;
                ob_flush();
                flush();
            }
            $index++;

            // 按$fields的顺序提取需要的字段值
            $rowData = [];
            foreach ($fields as $fieldKey => $fieldName) {
                $value = $item[$fieldKey] ?? '';
                // 检测长数字并格式化为文本
                if (is_numeric($value) && strlen((string)$value) > 8) {
                    $value = "=\"{$value}\"";
                }
                $rowData[] = $value;
            }

            fputcsv($fp, $rowData);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
}