单击链接后自动下载CSV文件


Auto download CSV file after link is clicked

我使用PHP创建csvs文件,将它们放入文件夹,然后压缩文件夹。这一切都很完美,但我无法让用户创建的ZIP自动下载。

编辑

它现在可以在进行重定向后工作,但在下载时缺少.zip扩展名,有办法强制这样做吗?

我的zip存储在根中的/zips中

这是我的代码

 // Add the folder we just created to a zip file.
$zip_name = 'groups_' . time();
$zip_directory = '/zips';
$zip = new zip( $zip_name, $zip_directory );
$zip->add_directory( 'group-csvs' );
$zip->save();
$zip_path = $zip->get_zip_path();
header( "Content-Description: File Transfer" );
header( "Content-type: application/zip" );
header( "Content-Disposition: attachment; filename=" . $zip_name . "");
header( "Content-Length: " . filesize( $zip_path ) );
readfile($zip_path);

这是我的zip类中的get-path方法和构造函数

   public function __construct( $file_name, $zip_directory)
   {
        $this->zip = new ZipArchive();
        $this->path = dirname( __FILE__ ) . $zip_directory . $file_name . '.zip';
        $this->zip->open( $this->path, ZipArchive::CREATE );
    }
   /**
     * Get the absolute path to the zip file
     * @return string
     */
    public function get_zip_path()
    {
        return $this->path;
    }   

我没有收到任何错误,它只是创建了zip,然后什么也没发生

在文件名中添加.zip扩展名:$zip_name = 'groups_' . time() . '.zip';您在自定义zip类中使用的扩展名没有附加到主文件中的变量。