Import and Export csv files
In work, you need to import csv file data to the database or export the database data as a csv file. The following is my simple implementation.
1 <? Php 2 class csv 3 {4 public $ db_connection; 5 public $ table_name; 6 public $ file_path; 7 8 public function _ construct ($ db_connection, $ table_name, $ file_path) 9 {10 $ this-> db_connection = $ db_connection; 11 $ this-> table_name = $ table_name; 12 $ this-> file_path = $ file_path; 13} 14 15/* 16 ** import the local csv file to the database 17 */18 public function import () 19 {20 $ SQL = "insert ". $ this-> table_name. "values"; 21 $ fp = fopen ($ this-> fil E_path, "r"); 22 if ($ fp) {23 while ($ data = fgetcsv ($ fp, 1000 ))! = FALSE) {24 $ values = "("; 25 $ num = count ($ data); 26 for ($ c = 0; $ c <$ num; $ c ++) {27 $ data [$ c] = str_replace ("'", "\'", $ data [$ c]); 28 $ values. = "'". $ data [$ c]. "',"; 29} 30 $ values = substr ($ values, 0, strlen ($ values)-1); 31 $ values. = "),"; 32 $ SQL. = $ values; 33} 34} 35 $ SQL = substr ($ SQL, 0, strlen ($ SQL)-1 ); 36 $ this-> db_connection-> exec ($ SQL); 37 fclose ($ fp); 38 echo "Fairy sister Liu Yifei, BI master's idol! "; 39} 40 41/* 42 ** export the database table to the local csv file 43 */44 public function export () 45 {46 $ fp = fopen ($ this-> file_path, "w"); 47 if ($ fp = TRUE) {48 $ SQL = "select * from ". $ this-> table_name. "limit 300"; 49 foreach ($ this-> db_connection-> query ($ SQL)-> fetchAll () as $ row) {50 $ I = 0; 51 foreach ($ row as $ key => $ value) {52 if ($ I % 2 = 0) {53 unset ($ row [$ key]); 54} 55 $ I ++; 56} 57 fputcsv ($ fp, $ row); 58} 59} 60 fclose ($ fp); 61 echo "Fairy Sister Liu Yifei, BI master's idol! "; 62} 63}