PHP 导出Csv

/**
     * 导出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;
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值