将多个CSV文件从MySQL导出为zip

时间:2014-08-12 00:06:14

标签: php mysql export-to-csv

主要编辑:我已经更新了我的代码,以便更好地包含Archive类以及ZIP下载。该表写入数据库就好了,但我的错误日志中出现错误,上面写着“没有这样的文件或目录”。我在哪里写每个表的文件?

非常感谢任何帮助/建议!

以下是我的代码:

HTML表单

if($_POST['submit']){   

if(empty($_POST['jobtitles'])) echo "<strong>Error: You have not entered a Job Title, please go back and enter one.</strong>";

else echo "<strong>Your documents are processing and being exported.</strong>";

}
?>


<body>
<center><strong><u>BLS Data Processor and Exporter</u></strong></center>

<form method="post" action="handler.php">

<p>Enter all of the desired jobs, each separated by a new line. Note: All jobs must be spelled exactly as contained in the BLS data</p>

<textarea name="jobtitles" rows="10" cols="50">
</textarea>


<p>Upon clicking submit, your tables will be generated and exported as a CSV file</p>

<p>Select the table types you would like to receive</p>

<input type="checkbox" name="tabletype[]" value="local">Local<br>
<input type="checkbox" name="tabletype[]" value="msa">MSA<br>
<input type="checkbox" name="tabletype[]" value="nmsa">NMSA<br>
<input type="checkbox" name="tabletype[]" value="state">State<br>
<input type="checkbox" name="tabletype[]" value="nat">National<br>

<input type="submit" value="Submit and Export">

</form>

</body>

PHP方

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");

// Create the ZIP file

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

    $pdo = new PDO("mysql:host=localhost;dbname=BLSdata","root","root");

    $tableList = $pdo->prepare('SHOW TABLES FROM BLSdata LIKE "localTable" AND "msaTable" AND "nmsaTable" AND "stateTable" AND "natTable"');
    $tableList->execute(array(''));

    // For each table

    foreach($tableList as $aTableList)
    {
        $content = export_table($aTableList[0]);
        $fileName = $aTableList[0].'.csv';
        $zip->addFile($fileName, $fileName);
    }
    $zip->close();
}
else
{
    echo 'Failed, code:' . $result_zip;
}
readfile($fileName);

$deleteLocal = "DROP TABLE localTable";

$pdo->query($deleteLocal);

exit();

0 个答案:

没有答案