public function readFile() { //用为用的是生成器,所以不用担心 csv 文件的大小 $handle = fopen(WEB_ROOT."abc.csv", 'rb'); while(feof($handle) === false) { yield fgetcsv($handle); } fclose($handle); } set_time_limit(0); #ini_set('memory_limit', '50M'); header ("content-type:text/html;charset=utf-8"); $insert_data = []; foreach($this->readFile() as $k=>$v) { if($k >= 2 && is_array($v)) { $v = self::convert_arr($v); //print_r($v);die; $v1 = strval($v[1]); if($v1 == '0') { $parent_id = 0; $path = 0; } else { $demo_arr = explode ('_', $v1); $parent_id = $demo_arr[0]; $path = implode('-',$demo_arr); } if(empty($v[4])) { continue; } $insert_data = [ 'id' => $v[0], 'parent_id' => $parent_id, 'path' => $path, //手机号 ' mobile ' => $v[4], //昵称 'nickname' => $v[21], //真实姓名 'realname' => $v[22], //注册时间 'create_time' => $v[45], 'pdd_pid' => $v[30], 'jd_pid' => $v[29], 'relation_id' => $v[70], ' number ' => getRandNumber(6), 'unionid' => $v[24], //头像 'avatar' => $v[32], ]; Db::name("members")->insert($insert_data); unset($insert_data); } } //编码转换 static function convert_arr($arr) { return array_map(function($v){ return mb_convert_encoding($v,'utf-8','gbk'); }, $arr); }
文章来源:智云一二三科技
文章标题:php 读取csv文件并保存到mysql数据库
文章地址:https://www.zhihuclub.com/77797.shtml