当前位置: 首页 > 后端技术 > PHP

yii框架将目录下的文件扫描到数据库中

时间:2023-03-29 13:46:33 PHP

需求:用yii框架写一个定时任务,扫描某个目录$target下的json文件,导入到指定的数据库中,实现:1.将需要存放的json文件放到指定目录$target下2.执行定时任务,导入mongo库Vote_teacher/opt/modules/php/bin/php/www/web/protected/yiic.phpimportVoteTeacher3。定时任务代码:/web/protected/commandsImportCommand.php/tmp/abc1.txt*/classImportCommandextendsCConsoleCommand{public$target='/www/web/html/import/';//扫描目录public$model;//存储数据库对象publicfunctionrun($args){if(isset($args[0])){$this->showMessage("paramserror",1);出口;}$this->model=$args[0];$this->导入();/***分析用户回答的信息,按格式存储vote_answer*@authorlizhihui*@date2018-4-9*/privatefunctionimport(){$files=scandir($this->target);//读取目录下的文件foreach($filesas$key=>$val){$val=pathinfo($val);$extension=$val['扩展名'];//过滤掉非json格式if($extension!='json'){continue;$filePath=$this->target.$val['basename'];$fp=fopen($filePath,'r');$内容='';while(!feof($fp)){$content.=fread($fp,filesize($filePath)/10);//每次读取文件的1/10//处理}$arr=json_decode($content);if(empty($arr)){$this->showMessage("没有要导入的数据");死();}//实例化不同的数据库$tag=true;foreach($arras$key=>$val){//存储$aVal=(array)$val;$model=new$this->model;if($modelinstanceofSMongodb){//动态字段存储foreach($aValas$k=>$v){$model->$k=$v;}}else{//非动态字段存储$model->attributes=$aVal;}if(!$model->save()){$tag=false;}else{未设置($模型);//销毁一个对象并在再次使用时创建一个新对象}}}if(!$tag){$this->showMessage("someerrorinimport");}else{$this->showMessage('导入成功!');}}/***消息输出*@authorlizhihui*@date2018-4-9*/privatefunctionshowMessage($str,$err=0){if(!$str){returnfalse;}if($err){echo"[ERROR]";}else{回声“[成功]”;}echodate("Y-m-dH:i:s",time())。”“。$海峡。"\n";}}