thinkphp导入文件

导入文件时,有TP自带的函数upload可以直接调用,自已写入一个导入的方法,以便前台显示的调用,其中要考虑到文件的去重,和文件日志的下载,下面是我所学期间所做的项目的

首先设置文件上传的方法

//导入文件
	 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->import($upload->rootPath.$info['file']['savepath'].$info['file']['savename']);
        }

       }

然后对文件导入进行处理,也就是去除重复的记录,同时需要检测字符串的编码,还有自动生成拼音

//检测字符串的编码
//$file文件名
 function detect_encoding($file) {
     $list = array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1');
     $str = file_get_contents($file);
     foreach ($list as $item) {
         $tmp = mb_convert_encoding($str, $item, $item);
         if (md5($tmp) == md5($str)) {
             return $item;
         }
     }
     return null;
}


// 应用公共文件
/**
 *  获取拼音信息
 *
 * @access    public
 * @param     string  $str  字符串
 * @param     int  $ishead  是否为首字母
 * @param     int  $isclose  解析后是否释放资源
 * @return    string
 */
function SpGetPinyin($str, $ishead=0, $isclose=1)
{
    //  return dirname(__FILE__).'/pinyin.dat';
    // exit;
    
    global $pinyins;
    $str = iconv('utf-8', 'gbk', $str);
    //die ($str);
    $restr = '';
    $str = trim($str);
    $slen = strlen($str);
    if($slen < 2)
    {
        return $str;
    }
    if(count($pinyins) == 0)
    {
        $fp = fopen(dirname(__FILE__).'/pinyin.dat', 'r');
        while(!feof($fp))
        {
            $line = trim(fgets($fp));
            $pinyins[$line[0].$line[1]] = substr($line, 3, strlen($line)-3);
        }
        fclose($fp);
    }
    for($i=0; $i<$slen; $i++)
    {
        if(ord($str[$i])>0x80)
        {
            $c = $str[$i].$str[$i+1];
            $i++;
            if(isset($pinyins[$c]))
            {
                if($ishead==0)
                {
                    $restr .= $pinyins[$c];
                }
                else
                {
                    $restr .= $pinyins[$c][0];
                }
            }else
            {
                $restr .= "_";
            }
        }else if( preg_match("/[a-z0-9]/i", $str[$i]) )
        {
            $restr .= $str[$i];
        }
        else
        {
            $restr .= "_";
        }
    }
    if($isclose==0)
    {
        unset($pinyins);
    }
    return $restr;
}

 public function import($file){
        $encoding=detect_encoding($file);
        if($encoding!='UTF-8'){
            $contens=file_get_contents($file);
            $contens=mb_convert_encoding($contens,'utf-8',$encoding);
            file_put_contents($file, $contens);
        }

        $fp=fopen($file, 'r');
        if($fp){
            $fields=array('no','name','sex');
            $model=M('student');
            $arrNo=$model->getField('no',true);//一维数组
            // dump($arrNo);
            // exit;
            $arr=array();
            $filename  =  './Public/Logs/demo.php' ;
            $fop=fopen($filename, 'w');
            while (($row=fgetcsv($fp,1000,","))!==false) {
                // $arr[]=array_combine($fields, $row);
                $row=array_combine($fields, $row);
                $name=$row['name'];
                $row['py']=SpGetPinyin($name);
                // dump($row);
                // exit;
                if(in_array($row['no'], $arrNo)){
                    
                    $data .= $row['no']."已存在\r\t";
                    $fwrite=fwrite($fop, $data);
                    // exit;
                }else{
                    $arr[]=$row;//将数据放入到二维数组
                    $arrNo[]=$row['no'];//将数据放入数据库中
                    // exit;
                     // echo $row['no']."导入成功.<br>";
                }
                if(count($arr)==1000){
                        $model->addAll($arr);
                        unset($arr);
                    }
                
            }

最后对已经处理过的进行写日志文件并将文件下载

//文件下载
               $file_name = "demo.php";
               $file_dir = "./Public/Logs/";
               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);
           
            if(count($arr)>0){
                $model->addAll($arr);
            }
            $this->show('添加成功','utf8');
        }

        }

猜你喜欢

转载自blog.csdn.net/ssh456/article/details/79738254
今日推荐