php扫描目录入库,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

/**

* 导入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";

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值