思想:首先上传文件,在检测内容的编码格式,更改成UTF8的格式,再打开文件,写入文件,首先把原表中的数据传入到一个数组,然后用循环(循环条件:产生有效的文件指针必须大于cvs文件内最长的一行,设置字段分解符)把数据写入文件中,其中循环中要判断原表中的数组与插入数据的数组是否存在相同的数据,如果有相同的数据则输出‘传入失败’,否则写入成功。
首先,写一个方法上传文件(代码):
public function upload(){ if(IS_GET){ $this->display(); exit; } $upload= new\Think\Upload();// $upload->maxSize=0;//设置最大长度 $upload->exts=array('csv'); $upload->rootPath='./Public/Upload/';//根目录路径 $upload->savePath=''; //上传文件 $info=$upload->upload(); if(!$info){ $this->error($upload->getError()); }else{ //$this->success('上传成功'.$info['file']['savepath'].$info['file']['savename']); // echo$upload->rootPath.$info['file']['savepath'].$info['file']['savename'],'utf8'; $this->import($upload->rootPath.$info['file']['savepath'].$info['file']['savename']); } }
写一个写入文件的方法,把上边的文件参数传到此方法中,
public functionimport($file){ //检测文件编码格式 $encoding = detect_encoding($file);//检测文件是什么编码格式 // dump($encoding); //如果不是utf8则转换为utf8 if ($encoding!='utf-8') { $content=file_get_contents($file);//将整个文件读入一个字符串 $content=mb_convert_encoding($content,'utf-8',$encoding);//将‘gbk'转换为'utf-8'. file_put_contents($file,$content);//将一个字符串写入文件 } //解析csv $fp=fopen($file, 'r');//只读方式打开,将文件指针指向文件头 if ($fp) { $arrNo=M('student')->getField('no',true);//一位数组获取原表所有的no存入数组 $filed=array('no','name','sex');//新建一个数组 $model=M('student');//实例化数据表 $arr=array();//创建一个空数组 while(($row=fgetcsv($fp,1000,','))){ //去重复 if(in_array($row['0'],$arrNo)){ $file="text.txt"; $content=$row['0'] . "学号已经存在!"; echo$content; //file_put_contents($file,$content); }else{ $arr[] =array_combine($filed, $row); $arrNo[]=$row['0']; $file="text.txt"; //$fp=fopen($file,'r'); $content=$row['0'].'导入成功'; echo$content; //file_put_contents($file,$content); } if(count($arr)==1000) { $model->addAll($arr); unset($arr); } } // fclose($file); if (count($arr)>0) { $model->addAll($arr); } $this->success('上传成功'); } }
构图: