Php file download function [real Project] sometimes requires such a function in the project: query the data in the database and save it to the csv file. Then download it to the client. Development ideas:
First, query the data to be queried from the database;
Write the data to be queried into the csv file;
3. save it to the client (browser );
The following code is used to simulate production (project:
"Liu dehua", "age" => 56, "work" => "acting"), array ("username" => "Zhang Xueyou", "age" => 55, "work" => "singing"),); $ filename = date('Ymd').'.csv '; data2csv ($ users, $ filename ); /*** @ param $ data array the data queried from the database * @ param $ download_file_name string file name downloaded by the client */function data2csv ($ data, $ download_file_name) {header ("Content-type: text/csv"); // Save the file type header ("Content-Disposition: attachment; filename = ". $ download_file_name); // Save the file name header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0'); header ('expires: 0 '); header ('pragma: public'); ob_start (); // enable ob cache echo "\ xEF \ xBB \ xBF"; $ df = fopen ("php: // output ", 'w'); $ head = array_keys (reset ($ data); fputcsv ($ df, $ head ); // save the first row of foreach ($ data as $ row) {fputcsv ($ df, $ row);} fclose ($ df); echo ob_get_clean ();}