Home > Backend Development > PHP Tutorial > Detailed example of how to generate .csv suffix file table in PHP

Detailed example of how to generate .csv suffix file table in PHP

零到壹度
Release: 2023-03-22 10:54:01
Original
2231 people have browsed it

This time I will bring you an example to explain in detail the table of .csv suffix file generated by PHP, mainly in the form of code. The following is a practical case. Follow the editor to take a look.

First understand how to generate a .csv file with a suffix

   # 数组,调用下面方法然后直接下载
    public function index(){
        $array = [
            ['name' => '张三','age' => 17],
            ['name' => '李四','age' => 18],
            ['name' => '王五','age' => 19],
            ['name' => '麻二','age' => 20],
        ];        return $this->export_csv($array);

    }
Copy after login

/***
     * 导出下载excel
     * @param [array] $array [要转换excel数组]
     */
    public function export_csv($array){
        $temp = '';        foreach ($array as $value)
        {            foreach ($value as $k => $val)
            {                $value[$k] = iconv('utf-8','gb2312',$value[$k]);
            }            $temp .= implode(",",$value)."\n"; //用英文“逗号”分开,获取值
        }        # 获取name,age做标题【这里我没有想到更好的方法,做个flag以便以后更加完善】
        ## 就是要取出 ‘name’,'age' 这两个key
        $keyname = array_keys($array[0])[0] . ',' . array_keys($array[0])[1] ."\n";        $string  = $keyname. $temp;//拼接

        $filename = date('Ymd').'.csv'; //设置文件名
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');        echo $string;
    }
Copy after login

The final exported excel is as follows:

Detailed example of how to generate .csv suffix file table in PHP

The above is a simple method to generate excel without using a class library!

Related recommendations:

PHP file export-Excel and csv

Use php to generate CSV files

Solution to Chinese garbled Chinese characters in PHP output csv file

The above is the detailed content of Detailed example of how to generate .csv suffix file table in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template