Php export csv file: specifies the encoding export and csv file import and export class

Source: Internet
Author: User
Tags export class
Php export csv file: specifies the encoding export and csv file import and export class

  1. /*
  2. * PHP code to export MySQL data to CSV
  3. *
  4. * Sends the result of a MySQL query as a CSV file for download
  5. * Easy to convert to UTF-8.
  6. */
  7. /*
  8. * Establish database connection
  9. */
  10. $ Conn = mysql_connect ('localhost', 'login', 'pass') or die (mysql_error ());
  11. Mysql_select_db ('database _ name', $ conn) or die (mysql_error ($ conn ));
  12. Mysql_query ("set names CP1252 ");
  13. /*
  14. * Execute SQL query
  15. */
  16. $ Query = sprintf ('select field1, field2 FROM table_name ');
  17. $ Result = mysql_query ($ query, $ conn) or die (mysql_error ($ conn ));
  18. /*
  19. * Send response headers to the browser
  20. * Following headers instruct the browser to treat the data as a csv file called export.csv
  21. */
  22. Header ('content-Type: text/csv; charset = cp1252 ');
  23. Header ('content-Disposition: attachment=filename=output.csv ');
  24. /*
  25. * Output header row (if atleast one row exists)
  26. */
  27. $ Row = mysql_fetch_assoc ($ result );
  28. If ($ row ){
  29. Echocsv (array_keys ($ row ));
  30. }
  31. /*
  32. * Output data rows (if atleast one row exists)
  33. */Export csv files
  34. While ($ row ){
  35. Echocsv ($ row );
  36. $ Row = mysql_fetch_assoc ($ result );
  37. }
  38. /*
  39. * Echo the input array as csv data maintaining consistency with most CSV implementations
  40. *-Uses double-quotes as enclosure when necessary
  41. *-Uses double-quotes to escape double-quotes
  42. *-Uses CRLF as a line separator
  43. */
  44. Function echocsv ($ fields)
  45. {
  46. $ Separator = '';
  47. Foreach ($ fields as $ field ){
  48. If (preg_match ('/\ r | \ n |, | "/', $ field )){
  49. $ Field = '"'. str_replace ('"', '""', $ field ).'"';
  50. }
  51. Echo $ separator. $ field;
  52. $ Separator = ',';
  53. }
  54. Echo "\ r \ n ";
  55. }
  56. ?>

II. php class for importing and exporting csv files

Php imports and exports csv files. Code:

  1. /**
  2. * CSV file processing class
  3. */
  4. Class Csv {
  5. Public $ csv_array; // csv array data
  6. Public $ csv_str; // csv file data
  7. Public function _ construct ($ param_arr, $ column ){
  8. $ This-> csv_array = $ param_arr;
  9. $ This-> path = $ path;
  10. $ This-> column = $ column;
  11. }
  12. /**
  13. * Export
  14. **/
  15. Public function export (){
  16. If (empty ($ this-> csv_array) | empty ($ this-> column )){
  17. Return false;
  18. }
  19. $ Param_arr = $ this-> csv_array;
  20. Unset ($ this-> csv_array );
  21. $ Export_str = implode (',', $ param_arr ['Nav']). "n ";
  22. Unset ($ param_arr ['Nav']);
  23. // Assemble data
  24. Foreach ($ param_arr as $ k => $ v ){
  25. Foreach ($ v as $ k1 => $ v1 ){
  26. $ Export_str. = implode (',', $ v1). "n ";
  27. }
  28. }
  29. // Export $ export_str
  30. Header ("Cache-Control: public ");
  31. Header ("Pragma: public ");
  32. Header ("Content-type: application/vnd. ms-excel ");
  33. Header ("Content-Disposition: attachment?filename=txxx.csv ");
  34. Header ('content-Type: APPLICATION/OCTET-STREAM ');
  35. Ob_start ();
  36. // $ File_str = iconv ("UTF-8", 'gbk', $ export_str );
  37. Ob_end_clean ();
  38. Echo $ export_str;
  39. }
  40. /**
  41. * Import
  42. **/
  43. Public function import ($ path, $ column = 3 ){
  44. $ Flag = flase;
  45. $ Code = 0;
  46. $ Msg = 'unprocessed ';
  47. $ Filesize = 1; // 1 MB
  48. $ Maxsize = $ filesize * 1024*1024;
  49. $ Max_column = 1000;
  50. // Check whether the file exists
  51. If ($ flag === flase ){
  52. If (! File_exists ($ path )){
  53. $ Msg = 'File does not exist ';
  54. $ Flag = true;
  55. }
  56. }
  57. // Check the file format
  58. If ($ flag === flase ){
  59. $ Ext = preg_replace ("/. *. ([^.] +)/", "$1", $ path );
  60. If ($ ext! = 'Csv '){
  61. $ Msg = 'only CSV files can be imported ';
  62. $ Flag = true;
  63. }
  64. }
  65. // Check the file size
  66. If ($ flag === flase ){
  67. If (filesize ($ path)> $ maxsize ){
  68. $ Msg = 'Imported file cannot exceed '. $ maxsize.' B file ';
  69. $ Flag = true;
  70. }
  71. }
  72. // Read the file
  73. If ($ flag = flase ){
  74. $ Row = 0;
  75. $ Handle = fopen ($ path, 'r ');
  76. $ DataArray = array ();
  77. While ($ data = fgetcsv ($ handle, $ max_column ,",")){
  78. $ Num = count ($ data );
  79. If ($ num <$ column ){
  80. $ Msg = 'The file does not meet the actual specifications: '. $ num.' column data ';
  81. $ Flag = true;
  82. Break;
  83. }
  84. If ($ flag === flase ){
  85. For ($ I = 0; $ I <3; $ I ++ ){
  86. If ($ row = 0 ){
  87. Break;
  88. }
  89. // Set up data
  90. $ DataArray [$ row] [$ I] = $ data [$ I];
  91. }
  92. }
  93. $ Row ++;
  94. }
  95. }
  96. Return $ dataArray;
  97. }
  98. }
  99. $ Param_arr = array (
  100. 'Nav' => array ('username', 'password', 'mailbox '),
  101. Array (0 => array ('xiaohai1', '20140901', 'xiaohai1 @ jbxue.com '),
  102. 1 => array ('xiaohai2 ', '000000', 'xiaohai2 @ jbxue.com '),
  103. 2 => array ('xiaohai3 ', '20140901', 'xiaohai3 @ jbxue.com ')
  104. ));
  105. $ Column = 3;
  106. $ Csv = new Csv ($ param_arr, $ column );
  107. // $ Csv-> export ();
  108. $ Path = 'C: \ Documents and Settings \ Administrator \ Temp \ txxx.csv ';
  109. $ Import_arr = $ csv-> import ($ path, 3 );
  110. Var_dump ($ import_arr );
  111. ?>

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.