php导出mongo日志,导出mongo库到本地
需求:
在yii框架架下,導(dǎo)出生產(chǎn)mongo庫中的數(shù)據(jù)到j(luò)son文件,下載到本地
調(diào)用:
1.在/web/Controllers/TestController.php下引用
public function actionExport()
{
public $target='/WWW/web/html/import/'; //windows 導(dǎo)出文件所在目錄
$export =new Export($target,'QuestionUser',96);
}
2.在/web/model下創(chuàng)建Export.php
/*導(dǎo)出mongo庫中的數(shù)據(jù)
* @author lizhihui
* @date 2018-5-29
* 調(diào)用例子:Export('MyModel',96); //導(dǎo)出數(shù)據(jù)庫MyModel中qId為96的數(shù)據(jù)
*/
Class Export
{
public $target;
public $model; //數(shù)據(jù)庫對象 string,例如:'QuestionAnswer','QuestionUser'
public $qId; //問卷id int
public $db;
/*
* $target 導(dǎo)出文件所在目錄
* $model
* $qId
*/
public function __construct($target,$model,$qId)
{
$this->target = $target;
$this->db=$model;
$this->model = new $model;
$this->qId = (int)$qId;
$this->export();
}
/**
* 導(dǎo)出mongo生產(chǎn)數(shù)據(jù)用于本地測試
* @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('數(shù)據(jù)為空');
}
$nStart = 0; //起始記錄
$nCount = 100; //每次處理記錄數(shù)
$nPage = intval($iCount/$nCount)+1;
$aReault=array();
for ($i=0;$i
$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;
//整理數(shù)據(jù),刪除不必要的鍵值
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('目標(biāo)文件不存在!');
}
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;
}
}
總結(jié)
以上是生活随笔為你收集整理的php导出mongo日志,导出mongo库到本地的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: anaconda python2.7,安
- 下一篇: oracle 最低要求吗,神谕Oracl