1

我在 PHP 中编写了一个脚本,以便在单击按钮时将 MySQL 表导出到 CVS 文件中。它工作正常,但现在我需要为每个 CSV 文件导出 1 个表,单击按钮时所有这些都在 ZIP(或 RAR)文件中。

基本上应该是: 导出表:

mytable.csv

导出所有表:

export.ZIP 包含:

--mytable1.csv

--mytable2.csv

--mytable3.csv

我可以为每个表循环导出函数,但这不会将所有内容放入 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();
}

我认为您不需要导出功能的所有代码,如果是,请告诉我。

谢谢!

4

1 回答 1

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);
于 2012-05-26T13:38:00.723 回答