使用PHP将多个.txt文件下载到.zip文件中

时间:2017-11-27 13:06:48

标签: php mysql

现在在系统中可以下载从MySQL表格行生成的.txt文件。我试图在一个zip文件中下载所有.txt文件。实际上,我坚持不确定我的方法是否可行。

 if (isset($_POST["ExportAll"])) {
    $query = $con->query("SELECT id, filename FROM thistable");

    $MultiArray = Array();
     while($result = $query->fetch_assoc()){
        $rowArray = Array();
        $rowArray[] = $result['id'];
        $rowArray[] = $result['filename'];
        $MultiArray[] = $rowArray;
    }

     foreach ($MultiArray as $arg) {
        $query = "SELECT * FROM thistable WHERE id LIKE '" . $arg[0] . "';";
        $result = mysqli_query($con, $query);
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $arg[1] );
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        $output = fopen("php://output", "w");

        while ($row = mysqli_fetch_assoc($result)) {

            foreach(array_slice($row,2) as $line) {
                echo ("$line \r\n");
            }
         }
        fclose($output);
     }
 }

可以将所有$output值放入某种$zipArray = Array()中,然后使用header("Content-type: application/zip");下载  ?

1 个答案:

答案 0 :(得分:2)

是的,您可以使用php ZipArchive类将多个文本文件作为单个zip文件下载。这只是您可以尝试使用自己的方案的示例。

 $zipname = 'sample.zip';
 $zip = new ZipArchive;
 $zip->open($zipname, ZipArchive::CREATE);
 $files_array = ["sample1", "sample2"]; // List of file names
 foreach ($files_array as $file) {
     $row = ["Line 1", "Line 2", "Line 3", "Line 5"]; // Assuming as your table row
     $filename = $file.".txt";
     $lines_to_add = "";
     foreach(array_slice($row, 2) as $line) {
         $lines_to_add .= $line."\r\n";
     }
     $zip->addFromString($filename, $lines_to_add);   // Adding lines to file
 }
 $zip->close();
 header('Content-Type: application/zip');
 header('Content-disposition: attachment; filename='.$zipname);
 header('Content-Length: ' . filesize($zipname));
 readfile($zipname);
 unlink($zipname); // Remove zip file if you don't want be in server