需求:在yii框架架下,导出生产mongo库中的数据到json文件,下载到本地
调用:1.在/web/controllers/testcontroller.php下引用
public function actionexport() { public $target='/www/web/html/import/'; //windows 导出文件所在目录 $export =new export($target,'questionuser',96); }
2.在/web/model下创建export.php
<?php/*导出mongo库中的数据* @author lizhihui * @date 2018-5-29* 调用例子:export('mymodel',96); //导出数据库mymodel中qid为96的数据*/class export{ public $target; public $model; //数据库对象 string,例如:'questionanswer','questionuser' public $qid; //问卷id int public $db; /* * $target 导出文件所在目录 * $model * $qid */ public function __construct($target,$model,$qid) { $this->target = $target; $this->db=$model; $this->model = new $model; $this->qid = (int)$qid; $this->export(); } /** * 导出mongo生产数据用于本地测试 * @author lizhihui * @date 2018-5-29 */ public function export() { $icount = $this->model->count(array( 'conditions'=>array( 'qid'=>array('equals' => $this->qid), )) ); if(!$icount){ $this->showmessage('数据为空'); } $nstart = 0; //起始记录 $ncount = 100; //每次处理记录数 $npage = intval($icount/$ncount)+1; $areault=array(); for ($i=0;$i<$npage;) { $swhere = array( 'conditions'=>array( 'qid'=>array('equals' => $qid), ), 'limit'=>$ncount, 'offset'=>$nstart, ); $arr = $this->model->findall($swhere); if(!is_dir($this->target)){ mkdir($this->target); } //写入文件 $limit = 1000;//每隔$limit行,刷新一下输出buffer,不要太大,也不要太小 foreach ($arr as $key => $val) { if($key!=0 && $key%$limit==0){ ob_flush(); flush(); } $attr=$val->attributes; //整理数据,删除不必要的键值 unset($attr['_id']); unset($attr['current_db']); unset($attr['pageinfo']); $areault[]=$attr; } $i++; $nstart = $i*$ncount; } $filepath=$this->target.$this->db.'_'.$this->qid.'.json'; file_put_contents($filepath,json_encode($areault)); //下载文件 if(!file_exists($filepath)){ $this->showmessage('目标文件不存在!'); } header('content-type: application/json'); header('content-disposition: attachment; filename='.$this->db.'_'.$this->qid.'.json'); header('accept-ranges: bytes'); echo file_get_contents($filepath); } /** * 信息输出 */ 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; exit; }}
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
在yii框架中扫描目录下文件入数据库的方法
关于yii2中gridview的用法总结
以上就是关于如何导出mongo库到本地的问题解决的详细内容。