This article mainly introduces how to export csv data in php to provide an example of downloading or saving csv data in a browser. For more information, see
1. provide download in the browser output
The code is as follows:
/**
* Export data to a CSV file
* @ Param array $ data
* @ Param array $ title_arr title
* @ Param string $ file_name CSV file name
*/
Function export_csv (& $ data, $ title_arr, $ file_name = ''){
Ini_set ("maid", "3600 ");
$ Csv_data = '';
/** Title */
$ Nums = count ($ title_arr );
For ($ I = 0; $ I <$ nums-1; ++ $ I ){
$ Csv_data. = '"'. $ title_arr [$ I]. '",';
}
If ($ nums> 0 ){
$ Csv_data. = '"'. $ title_arr [$ nums-1]." \ "\ r \ n ";
}
Foreach ($ data as $ k => $ row ){
For ($ I = 0; $ I <$ nums-1; ++ $ I ){
$ Row [$ I] = str_replace ("\" "," \ "\" ", $ row [$ I]);
$ Csv_data. = '"'. $ row [$ I]. '",';
}
$ Csv_data. = '"'. $ row [$ nums-1]." \ "\ r \ n ";
Unset ($ data [$ k]);
}
$ Csv_data = mb_convert_encoding ($ csv_data, "cp936", "UTF-8 ");
$ File_name = empty ($ file_name )? Date ('Y-m-d-H-I-s', time (): $ file_name;
If (strpos ($ _ SERVER ['http _ USER_AGENT '], "MSIE") {// Fix the Chinese name garbled by IE browser
$ File_name = urlencode ($ file_name );
$ File_name = str_replace ('+', '% 20', $ file_name );
}
$ File_name = $ file_name. '.csv ';
Header ("Content-type: text/csv ;");
Header ("Content-Disposition: attachment; filename =". $ file_name );
Header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0 ');
Header ('expires: 0 ');
Header ('pragma: public ');
Echo $ csv_data;
}
2. save to file
The code is as follows:
Function export_csv ($ data, $ title_arr, $ file_name = ''){
$ Csv_data = '';
/** Title */
$ Nums = count ($ title_arr );
For ($ I = 0; $ I <$ nums-1; ++ $ I ){
$ Csv_data. = '"'. $ title_arr [$ I]. '",';
}
If ($ nums> 0 ){
$ Csv_data. = '"'. $ title_arr [$ nums-1]." \ "\ r \ n ";
}
Foreach ($ data as $ k => $ row ){
For ($ I = 0; $ I <$ nums-1; ++ $ I ){
$ Row [$ I] = str_replace ("\" "," \ "\" ", $ row [$ I]);
$ Csv_data. = '"'. $ row [$ I]. '",';
}
$ Csv_data. = '"'. $ row [$ nums-1]." \ "\ r \ n ";
Unset ($ data [$ k]);
}
$ File_name = empty ($ file_name )? Date ('Y-m-d-H-I-s', time (): $ file_name;
File_put_contents ($ file_name, $ csv_data );
}
Call example(Save to file ):
The code is as follows:
$ File_name = "/var/www/tmp/test.csv ";
$ Header = array (
'0' => 'parameter ID ',
'1' => 'parameter name ',
'2' => 'statistical times ',
'3' => 'Count percentage ',
'4' => 'unique user size ',
'5' => 'percentage of unique users ',
'6' => 'average number'
);
$ CsvList = array ("111", "title", "12", "100%", "23", "50%", "4 "));
Export_csv ($ csvList, $ header, $ file_name );