Export csv files using php

Source: Internet
Author: User
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.
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.