dongzhenbi8919
2017-11-27 13:06
浏览 44
已采纳

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

Now in system it is possible to download .txt file generated from MySQL table row. I am trying to make it possible to download all .txt files in one zip file. Actually, I stuck on the point where I am not sure if my approach is possible.

 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 
");
            }
         }
        fclose($output);
     }
 }

It is possible to put all $output values into some kind of $zipArray = Array() and then download it with header("Content-type: application/zip"); ?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtypj3308 2017-11-27 13:30
    已采纳

    Yes you can download multiple text files as single zip file using php ZipArchive class. This is sample only you can try with your own scenario.

     $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."
    ";
         }
         $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
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题