• php中读取csv文件


      本来是想写在ecshop总结中的,发现内容有点多,于是单独出来,这样也清晰点。

      背景是将一个包含用户注册信息的csv文件读取,并将内容插入到users表中,即完成注册。整个过程是1.将文件上传到服务器上,2.根据名字来读取这个文件中内容,3.将得到的信息插入到数据库中。

      ②点击提交按钮后,php文件里的逻辑代码如下

    if ($_REQUEST['act'] == 'mc_add')
    {
        $link[] = array('text' => $_LANG['go_back'], 'href' => 'ck_user.php');
        //$upfile_flash
      
       
       if(!$_FILES['upfile']){
             sys_msg('没有上传文件;', 0, $link);
        }
          
       //文件上传
        $path = "../mc_upfile/".date("Ym")."/";
         //上传,备份;
        $file_chk=uploadfile("upfile",$path,'ck_user.php',1024000,'csv');  //1.上传文件
        if($file_chk){
            $filename = $path.$file_chk[0];
            //读取内容;
            //setlocale(LC_ALL,'zh_CN');
         $str = mc_read_txt($filename);
    $aData = getCSVdata($filename);                   //2.读取文件内容 //echo "<pre>"; //print_r($aData);//注册用户 if($str){ mc_reg_user($aData);                  //3.插入数据库 }else{ sys_msg('读取文件出错;', 0, $link); } sys_msg('恭喜,批量注册用户成功!', 0, $link); }else{ sys_msg('文件未上传成功;', 0, $link); } }

      ② function uploadfile 上传文件的方法如下。

    function uploadfile($upfile,$upload_path,$redirect,$f_size="102400",$f_type="txt,jpg|jpeg|gif|png"){
        if(!file_exists($upload_path)){
            mkdir($upload_path,0777);chmod($upload_path,0777);
        }//检测文件夹是否存,不存在则创建;
        $file_name=$_FILES[$upfile]['name'];
    
        if(empty($file_name))return false;
    
        $file_type=$_FILES[$upfile]['type'];
        $file_size=$_FILES[$upfile]['size'];
        $file_tmp=$_FILES[$upfile]['tmp_name'];
        $upload_dir=$upload_path;
    
        $ext=explode(".",$file_name);
        $sub=count($ext)-1;
        $ext_type=strtolower($ext[$sub]);//转换成小写
        $up_type=explode("|",$f_type);
        if(!in_array($ext_type,$up_type)){
            die("
                    <script language=javascript>
                 alert('您上传的文件类型不符合要求!请重新上传!\\n\\n上传类型只能是".$f_type."。');
                 location.href='".$redirect."';
                    </script>");
        }
    
        $file_names=time().rand(1,9999).".".$ext[$sub];
        $upload_file_name=$upload_dir.$file_names;
        $chk_file=move_uploaded_file($file_tmp,$upload_file_name);
        if($chk_file){ //判断文件上传是否成功
    
            chmod($upload_file_name,0777);//设置上传文件的权限
            unset($ext[$sub]);$file_name=implode(".",$ext);//先去除扩展名,后获取文件名
            return array($file_names,$file_size,$ext_type,$file_name);
        }else{
            return false;
        }
    }

      ③function getCSVdata 读取文件内容如下

    function getCSVdata($filename)
    {
        $row = 1;//第一行开始
        if(($handle = fopen($filename, "r")) !== false) 
        {    
            while(($dataSrc = fgetcsv($handle)) !== false) 
            {
                $num = count($dataSrc);
                for ($c=0; $c < $num; $c++)//列 column 
                {
                    if($row === 1)//第一行作为字段 
                    {
                        $dataName[] = $dataSrc[$c];//字段名称
                    }
                    else
                    {
                        foreach ($dataName as $k=>$v)
                        {
                            if($k == $c)//对应的字段
                            {
                                $data[$v] = $dataSrc[$c];
                            }
                        }
                    }
                }
                if(!empty($data))
                {
                     $dataRtn[] = $data;
                     unset($data);
                }
                $row++;
            }
            fclose($handle);
            return $dataRtn;
        }
    }

      ④function mc_reg_user  将数据插入到数据库

    function mc_reg_user($aData){
        foreach( $aData as $info )
        {
            $res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('users') ." WHERE user_name = '".$info[user_name]."' ");
            if(!$res){
                $sql = "insert into ".$GLOBALS['ecs']->table('users'). " set user_name='".$info['user_name']."'  , password ='".md5($info['password'])."'  , email ='".$info['email']."' , sex = '".$info['sex']."'  , user_money  ='".$info['user_money']."' , frozen_money ='".$info['frozen_money']."' , birthday
                = '".$info['birthday ']."'   , mobile_phone = '".$info['mobile_phone']."' , higherlevel_name = '".$info['higherlevel_name']."' , salesname = '".$info['salesname']."' , level = '".$info['level']."' , usertype = '".$info['usertype']."'  , typediscount = '".$info['typediscount']."'  ";
                $GLOBALS['db']->query($sql);
                if($info['user_money']>0){
                    //通过名字得到id号
                    $sql2 = "select user_id from ".$GLOBALS['ecs']->table('users'). " where user_name = '".$info[user_name]."' ";
                    $row = $GLOBALS['db']->getRow($sql2);
                    $accountlog_id = $row['user_id'];
                    $sql3 = "insert into ".$GLOBALS['ecs']->table('account_log'). "set user_id='".$accountlog_id."' ,user_money ='".$info['user_money']."' ,change_time='".gmtime()."' , change_desc ='生成账号时充值的金额' ";
                    $GLOBALS['db']->query($sql3);
                }
            }
        }
        
    }

      另外,还有一个判断,这个文件是否被读取的函数 function  mc_read_txt  代码如下

    function mc_read_txt($file){
        $pathfile=$file;
        if (!file_exists($pathfile)) {
          return false;
        }
        $fs = fopen($pathfile,"r+"); 
        $content = fread($fs,filesize($pathfile));//读文件
        fclose($fs);
        
        if(!$content) return false;    
        return $content;
    }

      至此,整个过程结束。

    在路上...
  • 相关阅读:
    json对象和字符串的相互转换
    使用link rel="shortcut icon"为网页标题加图标
    jQuery——Js与jQuery的相互转换
    用accessKey设置快捷键
    CSS :invalid 选择器
    创建并调用 DLL(1)
    调用外部 DLL 中的函数(2. 晚绑定)
    调用外部 DLL 中的函数(1. 早绑定)
    VCL 中的 Windows API 函数(6): BeginDeferWindowPos
    VCL 中的 Windows API 函数(5): AlphaBlend
  • 原文地址:https://www.cnblogs.com/chenkaiadd/p/3099027.html
Copyright © 2020-2023  润新知