这篇文章主要介绍了关于在yii框架中扫描目录下文件入数据库的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
需求:带yii框架下写一个定时任务,扫描某一目录$target下的json文件,并导入指定的数据库中
实现:1.把需要入库的json文件放在指定目录$target下
2.执行定时任务,导入到mongo库vote_teacher中
/opt/modules/php/bin/php /www/web/protected/yiic.php import voteteacher
3.定时任务代码:
/web/protected/commandsimportcommand.php
<?php/** * 导入mongo库到测试环境 * * @author lizhihui * @date 2018-4-9 * @console php www/web/protected/yiic.php import voteteacher> /tmp/abc1.txt */class importcommand extends cconsolecommand { public $target='/www/web/html/import/'; //扫描的目录 public $model; //入库的数据库对象 public function run($args) { if (isset($args[0])) { $this->showmessage(params error, 1); exit; } $this->model = $args[0]; $this->import(); } /** * 分析用户回答的信息并按格式入库vote_answer * @author lizhihui * @date 2018-4-9 */ private function import() { $files = scandir($this->target); //读取目录下文件 foreach ($files as $key => $val) { $val = pathinfo($val); $extension = $val['extension']; //过滤掉非json格式 if($extension!='json'){ continue; } $filepath=$this->target.$val['basename']; $fp=fopen($filepath,'r'); $content=''; while (!feof($fp)){ $content.=fread($fp, filesize($filepath)/10);//每次读出文件10分之1 //进行处理 } $arr=json_decode($content); if(empty($arr)){ $this->showmessage(no data to import); die(); } //实例化不同数据库 $tag=true; foreach ($arr as $key => $val) { //存储 $aval = (array)$val; $model = new $this->model; if($model instanceof smongodb){//动态字段存储 foreach ($aval as $k => $v) { $model->$k=$v; } }else{//非动态字段存储 $model->attributes=$aval; } if(!$model->save()){ $tag=false; }else{ unset($model); //销毁一个对象,再次使用的时候会new一个新的 } } } if(!$tag){ $this->showmessage(some error in import); }else{ $this->showmessage('import success!'); } } /** * 信息输出 * @author lizhihui * @date 2018-4-9 */ private function showmessage($str, $err = 0) { if (!$str) { return false; } if ($err) { echo [error]; } else { echo [success]; } echo date(y-m-d h:i:s, time()) . . $str . \n; }}
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
yii无法捕获到异常的解决方法
关于yii2加密和解密的介绍
以上就是在yii框架中扫描目录下文件入数据库的方法的详细内容。