2014-09-04 194 views
0

我已經搜索了互聯網,並且無法獲得關於它的任何具體細節。後一個用戶點擊submit按鈕,在MongoDB中的數據插入Name,Contact,Device,Email.Php MongoDB寫入CSV文件

環境是Windows 8WAMPMONGODB

我想設計一個網頁,其中有4場。所有這些工作正常。

這個問題從我嘗試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"); 

?> 

我已經啓用了桌面checbox互動我的WAMP服務器。

我不需要任何與編碼有關的具體幫助,我需要的是如何繼續前進的一些方向,因爲我知道我錯過了一些東西。另外,我重申,沒有在互聯網上得到任何具體的信息,因此發佈了這個問題。

請讓我知道如何做到這一點。

感謝大家

回答

1

此代碼將轉儲您選擇的數據庫到一個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())); 
+0

謝謝,我會試一試,並會接受答案。 :) – vamosrafa 2014-09-04 13:08:05

3

下可以工作

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"; 
+0

這一個很好,但我怎麼去下一個記錄是嵌入式,我在同一個記錄重試集合 – Shaggie 2016-04-13 12:21:48

+0

添加「\ n」在echo語句結尾的新行。編輯評論。 – 2016-04-29 09:46:14