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"; } }
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30