2012-05-24 58 views
0

我在PHP中完成了一個腳本,用於在單擊按鈕時將MySQL表導出爲CVS文件。它工作正常,但現在我需要爲每個CSV文件導出1個表格,點擊一個按鈕時,所有這些都在ZIP(或RAR)文件中。將CVS中的mysql表導出爲ZIP文件

基本上它應該是: 導出表:

mytable.csv

導出所有表:含有

export.ZIP:

--mytable1 .csv

--mytable2.csv

--mytable3.csv

我能環路輸出功能爲每個表,但不會把everyting到ZIP:

/* EXPORT ALL TABLES */ 
if (isset($_POST['export_all_tables'])){ 
    $Qlist_table = $pdo->prepare('SHOW TABLES'); 
    $Qlist_table->execute(array('')); 
    foreach ($Qlist_table as $Alist_table) 
     export_table($Alist_table[0]); 
} 


function export_table($table_to_export){ 
$Qselect = $pdo->prepare('SELECT * FROM '.$table_to_export.''); 
    $Qselect->execute(array('')); 
    $results = $Qselect->fetchAll(PDO::FETCH_ASSOC); 
... 
... 
... 

    header("Content-disposition: attachment; filename=".$fileName); 
    header("Content-Type: application/force-download"); 
    header("Content-Transfer-Encoding: application/vnd.ms-excel\n"); 
    header("Pragma: no-cache"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public"); 
    header("Expires: 0"); 

    echo $outputCsv; 
    exit(); 
} 

我不認爲你需要導出函數的所有代碼,如果是,請告訴我。

謝謝!

+1

你在哪裏把文件放到'.zip'? – mellamokb

+2

使用ZipArchive()類,並使用addFile()方法一次添加1個文件。 – goat

+0

我想直接下載文件。我現在使用affFile()。我會盡快更新我的問題! – remyremy

回答

0

其實我發現解決方案要歸功於addFile()。下面是代碼:

if (isset($_POST['export_all_tables'])){ 
    // Name of the file to export 
    $date = date('Y_m_j_H\hi'); 
    $fileName = 'Export_all_'.$date.'.zip'; 

    // Headers to create the ZIP file 
    header("Content-disposition: attachment; filename=".$fileName); 
    header("Content-Type: application/force-download"); 
    header("Content-Transfer-Encoding: application/zip;\n"); 
    header("Pragma: no-cache"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public"); 
    header("Expires: 0"); 

    // We create the ZIP file  
    $zip = new ZipArchive; 
    $result_zip = $zip->open($fileName, ZipArchive::CREATE); // We open the file 
    if ($result_zip === TRUE) { 

     $Qlist_table = $pdo->prepare('SHOW TABLES'); 
     $Qlist_table->execute(array('')); 

     // For each table 
     foreach ($Qlist_table as $Alist_table) { 

       $content = export_table($Alist_table[0]); 
       $fileName = $Alist_table[0].'_'.$date.'.csv'; 
       $zip->addFile($fileName, $fileName);   // We add the CSV file from the server 
     } 
     $zip->close(); 
    } 
    else { 
     echo 'Failed, code:' . $result_zip; 
    } 
    readfile("Export_all.zip");    // To download the ZIP file 
    exit(); 
} 

和exporttable函數結束這樣寫服務器上的文件:

$fh = fopen($fileName, 'w') or die("Can't open file"); 
$stringData = $outputCsv; // outputCsv is the content of the table 
fwrite($fh, $stringData); 
fclose($fh);