Php MongoDB编写CSV文件


Php MongoDB Write a CSV File

我在互联网上搜索过,但找不到任何关于它的具体细节。

环境为Windows 8WAMPMONGODB

我正在尝试设计一个网页,它有4个字段:Name,Contact,Device,Email.用户点击submit按钮后,数据插入MongoDb。所有这些都很好。

当我尝试write the inserted data in the csv file时,问题就开始了,因为这是要求。我尝试过MongoDB Export command in the cmd,它工作得很好,但使用exec function in the php script调用它是徒劳的。

我也尝试过,通过存储command in a .bat文件,然后使用php的exec函数调用.bat文件,仍然没有效果

<?php
echo '<pre>';
// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
exec("c:'WINDOWS'system32'cmd.exe /c START C:'wamp'bin'mongodb'mongodb-win32-x86_64-2008plus-2.4.3'conf'export.bat");
?>

我已经在WAMP服务器中启用了与桌面的checbox交互。

我不需要任何与编码相关的具体帮助,我只需要一些关于如何继续前进的指导,因为我知道我错过了一些东西。此外,我重申,在互联网上没有得到任何具体的信息,因此,我发布了这个问题。

请告诉我如何做到这一点。

感谢大家

以下可能适用于

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
$database   = "DATABASE";
$colName    = "COLLECTION";
$connection = new MongoClient();
$collection = $connection->$colName->$database;
$cursor     = $collection->find();
foreach($cursor as $cur)
   echo '"'.$cur['field_1'].'","'.$cur['field_2']."'"'n";

此代码将把您选择的数据库转储到json文件

$mongoExport = 'c:'mongodb'mongoexport'; //full path to mongoexport binary
$database = 'test';
$collection = 'foo';
$file = "c:''temp''foo.json"
exec(sprintf("%s -d %s -c %s -o %s",
    $mongoExport,
    $database,
    $collection,
    $file
));

这是使用纯PHP,当然会更快的mongoexport选项,具有大集合:

$database = 'test';
$collection = 'foo';
$m = new MongoClient();
$col = $m->selectDB($database)->$collection;
$json = json_encode(iterator_to_array($col->find()));
set_time_limit(0);
ob_start();
error_reporting(E_ALL);
ini_set("display_errors",1);
$conn = new MongoClient("mongodb://Hostname:27017", array("replicaSet" => "rs0"));
if(!$conn){
    die("Unable to connect with mongodb");
}
$db = $conn-><DB NAME>; // DB name
$col1 = $db-><colname>;
$col2 = $db-><colname>; // collection name which u want .
$filterCountry = array("status"=>"1"); // where query
$records = $col1->find($filterCountry);

$fp= fopen('exampleTest11.csv', 'w'); // open csv file in which u want write data.
$headings[] = "Code";   
$headings[] = "Status" ; 
$headings[] = "EMP CODE";
fputcsv($fp, $headings);      // PUT Headings .
$cnt =0;     
foreach($records as $val)   {
    $csvarr = array();
    $csvarr['code']= $val['code'];  // fetch data from database.
    $csvarr['Status']= $val['status'];
    $csvarr['emp_code']= $val['emp_code'];
    fputcsv($fp, $csvarr);
    $cnt++;
}

echo "Completed Successfully..".$cnt;