1

ボタンをクリックしたときにMySQLテーブルをCVSファイルにエクスポートするスクリプトをPHPで実行しました。正常に動作していますが、ボタンをクリックすると、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 に答える