- /*
- * PHP code to export MySQL data to CSV
- *
- * Sends the result of a MySQL query as a CSV file for download
- * Easy to convert to UTF-8.
- */
-
- /*
- * Establish database connection
- */
-
- $ Conn = mysql_connect ('localhost', 'login', 'pass') or die (mysql_error ());
- Mysql_select_db ('database _ name', $ conn) or die (mysql_error ($ conn ));
- Mysql_query ("set names CP1252 ");
- /*
- * Execute SQL query
- */
- $ Query = sprintf ('select field1, field2 FROM table_name ');
- $ Result = mysql_query ($ query, $ conn) or die (mysql_error ($ conn ));
- /*
- * Send response headers to the browser
- * Following headers instruct the browser to treat the data as a csv file called export.csv
- */
- Header ('content-Type: text/csv; charset = cp1252 ');
- Header ('content-Disposition: attachment=filename=output.csv ');
- /*
- * Output header row (if atleast one row exists)
- */
-
- $ Row = mysql_fetch_assoc ($ result );
- If ($ row ){
- Echocsv (array_keys ($ row ));
- }
-
- /*
- * Output data rows (if atleast one row exists)
- */Export csv files
- While ($ row ){
- Echocsv ($ row );
- $ Row = mysql_fetch_assoc ($ result );
- }
-
- /*
- * Echo the input array as csv data maintaining consistency with most CSV implementations
- *-Uses double-quotes as enclosure when necessary
- *-Uses double-quotes to escape double-quotes
- *-Uses CRLF as a line separator
- */
-
- Function echocsv ($ fields)
- {
- $ Separator = '';
- Foreach ($ fields as $ field ){
- If (preg_match ('/\ r | \ n |, | "/', $ field )){
- $ Field = '"'. str_replace ('"', '""', $ field ).'"';
- }
- Echo $ separator. $ field;
- $ Separator = ',';
- }
- Echo "\ r \ n ";
- }
- ?>
II. php class for importing and exporting csv files Php imports and exports csv files. Code:
- /**
- * CSV file processing class
- */
- Class Csv {
- Public $ csv_array; // csv array data
- Public $ csv_str; // csv file data
- Public function _ construct ($ param_arr, $ column ){
- $ This-> csv_array = $ param_arr;
- $ This-> path = $ path;
- $ This-> column = $ column;
- }
- /**
- * Export
- **/
- Public function export (){
- If (empty ($ this-> csv_array) | empty ($ this-> column )){
- Return false;
- }
- $ Param_arr = $ this-> csv_array;
- Unset ($ this-> csv_array );
- $ Export_str = implode (',', $ param_arr ['Nav']). "n ";
- Unset ($ param_arr ['Nav']);
- // Assemble data
- Foreach ($ param_arr as $ k => $ v ){
- Foreach ($ v as $ k1 => $ v1 ){
- $ Export_str. = implode (',', $ v1). "n ";
- }
- }
- // Export $ export_str
- Header ("Cache-Control: public ");
- Header ("Pragma: public ");
- Header ("Content-type: application/vnd. ms-excel ");
- Header ("Content-Disposition: attachment?filename=txxx.csv ");
- Header ('content-Type: APPLICATION/OCTET-STREAM ');
- Ob_start ();
- // $ File_str = iconv ("UTF-8", 'gbk', $ export_str );
- Ob_end_clean ();
- Echo $ export_str;
- }
- /**
- * Import
- **/
- Public function import ($ path, $ column = 3 ){
- $ Flag = flase;
- $ Code = 0;
- $ Msg = 'unprocessed ';
- $ Filesize = 1; // 1 MB
- $ Maxsize = $ filesize * 1024*1024;
- $ Max_column = 1000;
-
- // Check whether the file exists
- If ($ flag === flase ){
- If (! File_exists ($ path )){
- $ Msg = 'File does not exist ';
- $ Flag = true;
- }
- }
- // Check the file format
- If ($ flag === flase ){
- $ Ext = preg_replace ("/. *. ([^.] +)/", "$1", $ path );
- If ($ ext! = 'Csv '){
- $ Msg = 'only CSV files can be imported ';
- $ Flag = true;
- }
- }
- // Check the file size
- If ($ flag === flase ){
- If (filesize ($ path)> $ maxsize ){
- $ Msg = 'Imported file cannot exceed '. $ maxsize.' B file ';
- $ Flag = true;
- }
- }
- // Read the file
- If ($ flag = flase ){
- $ Row = 0;
- $ Handle = fopen ($ path, 'r ');
- $ DataArray = array ();
- While ($ data = fgetcsv ($ handle, $ max_column ,",")){
- $ Num = count ($ data );
- If ($ num <$ column ){
- $ Msg = 'The file does not meet the actual specifications: '. $ num.' column data ';
- $ Flag = true;
- Break;
- }
- If ($ flag === flase ){
- For ($ I = 0; $ I <3; $ I ++ ){
- If ($ row = 0 ){
- Break;
- }
- // Set up data
- $ DataArray [$ row] [$ I] = $ data [$ I];
- }
- }
- $ Row ++;
- }
- }
- Return $ dataArray;
- }
- }
- $ Param_arr = array (
- 'Nav' => array ('username', 'password', 'mailbox '),
- Array (0 => array ('xiaohai1', '20140901', 'xiaohai1 @ jbxue.com '),
- 1 => array ('xiaohai2 ', '000000', 'xiaohai2 @ jbxue.com '),
- 2 => array ('xiaohai3 ', '20140901', 'xiaohai3 @ jbxue.com ')
- ));
- $ Column = 3;
- $ Csv = new Csv ($ param_arr, $ column );
- // $ Csv-> export ();
- $ Path = 'C: \ Documents and Settings \ Administrator \ Temp \ txxx.csv ';
- $ Import_arr = $ csv-> import ($ path, 3 );
- Var_dump ($ import_arr );
- ?>
|