Php exports a csv file, because it needs to export a copy of data for the company and looks for a lot of information, many do not understand, many still have Encoding Problems, messy seven or eight slots, although this document is also for reference
Because it is easy to use, you can keep one copy!
Export_csv ();
Function export_csv (){
$ Filename = date ('ymdhis '). ". csv"; // file name
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 array_to_string (get_export_data ());
}
Function array_to_string ($ result ){
If (empty ($ result )){
Return I ("no data that meets your requirements! __^ ");
}
$ Data = 'book ID, title '. "\ n"; // topic name
$ Size_result = sizeof ($ result );
For ($ I = 0; $ I <$ size_result; $ I ++ ){
$ Data. = I ($ result [$ I] ['name']). ','. I ($ result [$ I] ['option']). "\ n ";
}
Return $ data;
}
Function get_export_data (){
$ Link = mysql_connect ('localhost', 'root', '121051xz ') or die (mysql_error ());
Mysql_select_db ('ht ');
Mysql_query ("set names 'utf8'"); // defines the encoding.
$ SQL = 'select * from booklist ';
$ Result = mysql_query ($ SQL );
$ Rowaa = mysql_fetch_array ($ result );
$ Res = array ();
$ I = 0;
While ($ row = mysql_fetch_array ($ result )){
$ Res [$ I] ['name'] = $ row ['bookid'];
$ Res [$ I] ['option'] = $ row ['bookname'];
$ I ++;
}
Return $ res;
}
Function I ($ strInput ){
Return iconv ('utf-8', 'gb2312', $ strInput); // this parameter is used when the page encoding is UTF-8. Otherwise, the exported Chinese characters are garbled.
}