【问题标题】:Add excel file to password protected zip?将 excel 文件添加到受密码保护的 zip 中?
【发布时间】:2020-06-11 09:28:38
【问题描述】:

如何将生成的 excel 文件添加到受密码保护的 zip 并下载? 我正在使用 ZipArchive 库。我正在尝试将 excel 文件添加到 zip,但不幸的是 zip 没有生成。

if(isset($_POST["export_excel"]))
{
    $sql = "SELECT * FROM Datas ORDER BY ID DESC";
    $result = mysqli_query($connect, $sql);
    ....
    ....
    ....
        $output .= '</table>';
        $fileName = "DB".date('Y_m_d').".xls";
        header("Content-Type: application/xls");
        header("Content-Disposition: attachment; filename=$fileName");
        echo $output;

        $zip = new ZipArchive;
        $tmp_file = 'myzip.zip';
        if ($zip->open($tmp_file,  ZipArchive::CREATE)) {
        $zip->setPassword>addFile('PASSWORD', $fileName); 
        $zip->setEncryptionName($fileName, ZipArchive: header('Content-disposition:EM_AES_256 attachment; filename=files.zip'); 
        header('Content-type: application/zip');
        $zip->close();
        readfile($tmp_file);

    }
}

【问题讨论】:

  • 标头类型可能不正确,您实际上并没有输出 zip 文件,stackoverflow.com/a/12226067/1213708
  • @NigelRen 我已经按照链接更新了代码。生成了 zip,但不幸的是 zip 无效。我假设该文件永远不会被添加。我在这里做错了什么?
  • 而不是 echo 电子表格的内容,这可能需要写入文件 (file_put_contents($fileName, $output);),然后将此文件添加到 zip 文件中。
  • @NigelRen 知道了!谢谢你:)

标签: php ziparchive


【解决方案1】:

我明白了。如果有人需要,逻辑是在excel中添加数据库的内容,然后输出。


       $output .= '</table>';
        $fileName = "DB".date('Y_m_d').".xls";
        header("Content-Type: application/xls");
        header("Content-Disposition: attachment; filename=$fileName");
        //echo $output;
        file_put_contents($fileName, $output);


    }

}

$zip = new ZipArchive;
$tmp_file = 'myzip.zip';
if ($zip->open($tmp_file,  ZipArchive::OVERWRITE|ZipArchive::CREATE)) {
    $zip->setPassword('PASSWORD');
    $zip->addFile($fileName);
    $zip->setEncryptionName($fileName, ZipArchive::EM_AES_256);
    header('Content-disposition: attachment; filename=files.zip');
    header('Content-type: application/zip');

    readfile($tmp_file);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多