在工作中需要把csv文件数据导入数据库或者把数据库数据导出为csv文件。以下是我的简单的实现。
<?php class csv { public $db_connection; public $table_name; public $file_path; public function __construct($db_connection,$table_name,$file_path) { $this->db_connection=$db_connection; $this->table_name=$table_name; $this->file_path=$file_path; } /* **把本地csv文件导入数据库 */ public function import() { $sql="insert ".$this->table_name." values "; $fp=fopen($this->file_path, "r"); if($fp){ while(($data=fgetcsv($fp,1000))!==FALSE){ $values="("; $num=count($data); for($c=0;$c<$num;$c++){ $data[$c]=str_replace("'", "\'", $data[$c]); $values.="'".$data[$c]."',"; } $values=substr($values,0,strlen($values)-1); $values.="),"; $sql.=$values; } } $sql=substr($sql,0,strlen($sql)-1); $this->db_connection->exec($sql); fclose($fp); echo "Fairy sister Liu Yifei, BI master's idol!"; } /* **把数据库表导出到本地csv文件 */ public function export() { $fp=fopen($this->file_path, "w"); if($fp==TRUE){ $sql="select * from ".$this->table_name." limit 300"; foreach($this->db_connection->query($sql)->fetchAll() as $row){ $i=0; foreach ($row as $key => $value) { if($i%2==0){ unset($row[$key]); } $i++; } fputcsv($fp,$row); } } fclose($fp); echo "Fairy sister Liu Yifei, BI master's idol!"; } }