Home >Backend Development >PHP Tutorial >Detailed example of how to generate .csv suffix file table in PHP
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); }
/*** * 导出下载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; }
The final exported excel is as follows:
The above is a simple method to generate excel without using a class library!
Related recommendations:
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!