• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

在yii框架中扫描目录下文件入数据库的方法

php 搞代码 4年前 (2022-01-21) 20次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了关于在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 CConsol<strong>*本文来@源gao@daima#com搞(%代@#码@网2</strong><pre>搞代gaodaima码

eCommand { 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无法捕获到异常的解决方法

以上就是在yii框架中扫描目录下文件入数据库的方法的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:在yii框架中扫描目录下文件入数据库的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址