Sometimes you need a feature in your project: After querying the data in the database, save it in a CSV file. Then download to the client. Development ideas:
First, the need to query the data from the database query out;
Write the data that needs to be queried into the CSV file;
3. Save to client (browser);
To simulate the production (project) situation, the code listing is as follows:
"Andy Lau", "Age" =>56, "work" and "play"), Array ("username" = "Jacky", "Age" =>55, "work" and "singing"); $filename = Date (' Ymd '). CSV '; Data2csv ($users, $filename); /** * @param $data array data queried from the database * @param $download _file_name string client after download * * Function data2csv ($data, $download _file_name) {Header ("content-type:text/csv"); Save file Type header ("Content-disposition:attachment;filename=". $download _file_name);//The name of the file to save the header (' Cache-con Trol:must-revalidate,post-check=0,pre-check=0 '); Header (' expires:0 '); Header (' Pragma:public '); Ob_start ();//Open OB cache echo "\XEF\XBB\XBF"; $DF = fopen ("Php://output", ' W '); $head = Array_keys (Reset ($data)); Fputcsv ($DF, $head);//Save the first line of foreach ($data as $row) {fputcsv ($DF, $row); } fclose ($DF); Echo Ob_get_clean (); }