Source: http://www.jb51.net/article/49313.htm
1. Download available in browser output
/** * Export Data to CSV file * @param array $data data * @param array $title _arr title * @param string $file _name CSV file name */function Export _csv (& $data, $title _arr, $file _name = ") {Ini_set (" Max_execution_time "," 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")) {//resolve bug $file _name = UrlEncode ($file _name) for IE output Chinese name garbled $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
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);}
Invoke Example (save to file):
$file _name= "/var/www/tmp/test.csv"; $header = Array ( ' 0 ' = ' parameter id ', ' 1 ' = ' parameter name ', ' 2 ' = ' count '), c3/> ' 3 ' = ' percent of statistics ', ' 4 ' = ' unique users ', ' 5 ' + ' unique user percentage ', ' 6 ' = ' per capita ' ; $csvList = Array ("111", "title", "N", "100%", "Up", "50%", "4")); Export_csv ($csvList, $header, $file _name);
PHP export CSV data in the browser output provides an example of downloading or saving to a file