2010-03-01 91 views
1

我想從我的MySQL數據庫導出數據到多個CSV文件,然後GZIP他們。PHP的CSV導出功能

我有一對夫婦的問題,這使得它導出爲CSV文件複雜...

  1. 幾個字段(10)需要在1個CSV文件
  2. 其他領域(多!)是序列化並需要導出到另一個CSV文件中,該文件中包含另外兩個非序列化字段。

我想要做的就是將所有這些CSV文件創建在gzip文件中......這就是我到目前爲止所做的!會發生什麼用戶檢查不同的複選框,他們想要導出哪個文件。然後傳遞給這個文件,每個文件有不同的SELECT查詢和字段名稱。我甚至還沒有開始處理序列化的數據......我不知道我將如何去做。然後它返回CSV文件,並將該文件放入一個等待導出到gzip的數組中......甚至不知道我是否可以這樣做。

任何建議或幫助將不勝感激!

$files = array(); 

if(in_array("general", $_POST['exportid'])){ 
$files[] = CSVoutput("SELECT timestamp, id, monday, tuesday, wednesday, thursday, friday, saturday, sunday, records, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 23, 24 FROM hourly", array(timestamp, id, monday, tuesday, wednesday, thursday, friday, saturday, sunday, records, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 23, 24)); 
} 

function CSVoutput($query, $fields){ 
$rsSearchResults = mysql_query($query) or die(mysql_error()); 

$out = ''; 
$columns = count($fields); 

// Put the name of all fields 
for ($i = 0; $i < $columns; $i++) { 
$l= $fields[$i]; 
$out .= '"'.$l.'",'; 
} 
$out .="\n"; 

// Add all values in the table 
while ($l = mysql_fetch_array($rsSearchResults)) { 
for ($i = 0; $i < $columns; $i++) { 
$out .='"'.$l["$i"].'",'; 
} 
$out .="\n"; 
} 
return $out; 
} 
exit; 

回答

2

查看fputcsv()函數。它會處理報價/轉義比你擁有的要好得多。

res = query_result 
row = fetch array from res 

handle/remove serialized columns in row 
fputcsv(row array keys) 
fputcsv(row values) 

while(row = fetch from res) 
    handle/remove serialized columns in row 
    fputcsv(row values) 
+0

有關如何在腳本中實現該功能的任何建議? – 2010-03-01 08:35:47

+1

我不喜歡爲人編寫代碼,但我正在編輯一些僞代碼 – 2010-03-01 09:02:20

+0

這真的很有幫助。謝謝 – 2010-03-02 06:35:57

-1

也許你有做這種方式的一個原因,但我只是想提一提,SELECT ... INTO OUTFILE出口選擇的結果到CSV文件中。

您還可以指定字段的分隔方式等。所以你可能想嘗試一下。

也看到這個頁面(向下滾動到SELECT INTO OUTFILE) http://dev.mysql.com/doc/refman/5.1/en/select.html

如果您需要手動執行此操作,那麼請忽略我的意見。

+0

好主意......只要我有文件訪問我的MySQL服務器...... ;-D – 2010-03-01 08:36:11

+0

在文件寫入後,您可以打開它與PHP並顯示它。或者PHP不是和MySQL一樣運行在同一臺服務器上? – 2010-03-01 08:52:36

+0

MySQL服務器位於不同的服務器上... – 2010-03-02 06:35:34