在工作中需要把csv文件數據導入數據庫或者把數據庫數據導出為csv文件。以下是我的簡單的實現。
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 **把本地csv文件導入數據庫 17 */ 18 public function import() 19 { 20 $sql="insert ".$this->table_name." values "; 21 $fp=fopen($this->file_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 **把數據庫表導出到本地csv文件 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 }