关于tp3.2.3文件导入数据库(去除重复数据)、写日志和下载问题

   假设我们有一个student.csv文件和一个student库,现在要将student.csv文件导入数据库。

1.关于去掉重复数据导入数据库的基本思路

      (1)首先我们将student数据库里的学号(no)取出来,放在$arrNo数组里。

      (2)然后,我们再将csv文件的学号(no)取出来,判断学号(no)是否存在$arrNo数组。

       (3)如果学号在$arrNo数组中不存在,则将学号(no)追加到$arrNo,然后将记录存放到$arr数组。如果存在,则不插入。

2.现在我们有一个上传文件的一个页面:

       <form action="__URL__/upload" style="text-decoration:center;" enctype="multipart/form-data" method="post">
                     <input type="file" name="photo" ><br>
                     <input type="submit" value="导入" style="margin:0 auto;">
                     <input type="button" value="取消"  data-dismiss="modal">

        </form>

注意:enctype="multipart/form-data"这个是上传文件必写的一个属性。

3.然后我们在控制器写一个上传的upload方法:

      public function upload(){
              $upload = new \Think\Upload();// 实例化上传类
              $upload->maxSize = 0 ;// 设置附件上传大小
              $upload->exts = array('csv');// 设置附件上传类型
              $upload->rootPath = './Uploads/'; // 设置附件上传根目录

              $upload->savePath = ''; // 设置附件上传(子)目录

              $info = $upload->upload();//获取上传的信息

              if(!$info) {// 上传错误提示错误信息
	           $this->error($upload->getError());
	      }else{// 上传成功
	           $this->import($upload->rootPath.$info['file']['savepath'].$info['file']['savename']);

	               }

             }

     }

4.在控制器写一个导入数据库的import方法:

       public function import($file){

              $encoding=detect_encoding($file);
              //如果不是utf8格式,则转换为utf8
                   if($encoding != 'UTF-8'){
                       $contens=file_get_contents($file);
                       $contens=mb_convert_encoding($contens, 'utf-8',$encoding);
                       file_put_contents($file, $contens);

                   }

                         $student=M('student');

                         $arrNo=$student->getField('no',true);

                         $fp=fopen($file,'r');//以读的方式打开

                              if($fp){
                  	           $fields=array('no','name','sex');
		                   $model=M('student');
		                   $arrNo=$model->getField('no',true);
		                    // dump($arrNo);

		                   $arr=array();//定义一个空数组

                                   $i=1;//定义行数

                                       while (($row=fgetcsv($fp,1000,","))!==false) {
		                	      $row=array_combine($fields, $row);
		                	      // dump($row);
			                             if (in_array($row['no'], $arrNo)) {//判断csv的学号在数据库中是否存在
			                                  $tr.= '第'.$c.'行'.$row['no']."存在\r\n";
			                             }else{
			                                   $arrNo[]=$row['no'];
			                                   $arr[]=$row;
			                                   $tr.='第'.$c.'行'.$row['no']."导入成功\r\n";        
			                 }
			                                   if (count($arr)==1000) {
			                                       $model->addAll($arr);
			                                       unset($arr);
			                                       $this->show('导入成功','student/index');

			                                     }

                                                                 $i++;

			               }

                                                                     $data=writelog("myerror",$tr);//调用写日志方法
				                                          if (count($arr)>0) {
				                                              $model->addAll($arr);
				                                              $this->success('导入成功','index');
				                                         }else{
                                                                              $this->error('数据库已存在');
				                                          }

                            }

                    }

        }

    在function.php中写一个写日志函数:

                 function writelog($type="",$content=""){
                         if(!$content || !$type){
                                 return false;
                        }    
                               $dir=getcwd().DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.$type;
                                      if(!is_dir($dir)){ 
                                           if(!mkdir($dir)){
                                                 return false;
                                           }
                                      }
                                           $filename=$dir.DIRECTORY_SEPARATOR.date("Ymd",time()).'.log';   
                                            $logs=include $filename;
                                                    if($logs && !is_array($logs)){
                                                              unlink($filename);
                                                             return false;
                                                    }
                                                                $logs=$content;
                                                               $str=var_export($logs, true).";";
                                                                       if(!$fp=@fopen($filename,"wb")){
                                                                                 return false;
                                                                         }           
                                                                               if(!fwrite($fp, $str))return false;
                                                                                     fclose($fp);
                                                                                      return true;

                                                                             }

      最后我们在控制器写一个下载的方法:

               public function xia(){
                           $file_dir = "./Logs/myerror/"; 
			               $file_name = date("Ymd",time()).'.log'; 
                                             if (!file_exists ($file_dir.$file_name )) {    
							    echo "文件找不到";    
							    exit ();    
							} else {    
							    //打开文件    
							    $file = fopen ( $file_dir . $file_name, "r" );    
							    //输入文件标签     
							    Header ( "Content-type: application/octet-stream" );    
							    Header ( "Accept-Ranges: bytes" );    
							    Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) );    
							    Header ( "Content-Disposition: attachment; filename=" . $file_name );    
							    //输出文件内容     
							    //读取文件内容并直接输出到浏览器    
							    echo fread ( $file, filesize ( $file_dir . $file_name ) );    
							    fclose ( $file );    
							    exit ();    
							} 

               }

  然后我们可以在模板文件中加一个<a href="__URL__/xia">下载</a>,这样就可以实现下载功能。

             

    

猜你喜欢

转载自blog.csdn.net/mo3408/article/details/79729205