2

我有一些 pdf 文件...我只想将它们作为一个集合下载,而不是一个一个地下载。为此,我正在尝试压缩所有 pdf 文件并下载。但我不知道为什么在我的代码中更改 ZipArchive 文件名时,它说已损坏和损坏。我的代码如下: -

 function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
    $zip = new ZipArchive();
    //create the file and throw the error if unsuccessful
    if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE )!==TRUE) {
        exit("cannot open <$archive_file_name>\n");
    }
    //add each files of $file_name array to archive
    foreach($file_names as $files)
    {
        $zip->addFile($file_path.$files,$files);

    }
    $zip->close();
    //then send the headers to foce download the zip file
    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=$archive_file_name"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    readfile("$archive_file_name"); 
    exit;
}



if($button=="Save as pdf")
{
$file_names = array();
foreach($a as $key=>$as)
{
 $file_names[] = $key.'.pdf';
}
}
$archive_file_name='zipped.zip';
$file_path='/resume/';
zipFilesAndDownload($file_names,$archive_file_name,$file_path);

?>

有人可以帮帮我吗?提前致谢。

它工作正常,但我仍然面临 2 个问题,1。如果我将archive_file_name 的名称更改为上面给出的名称以外的名称,我会收到Archive 已损坏的错误消息。我不知道为什么会这样 2.如果我有一个 zip 文件,比如说 2 个 pdf,然后我再次下载一个只有 1 个 pdf 的 zip,这与以前的不一样。但是当我下载 1 个 pdf 的 zip 时,我得到了 3 个 pdf ......我不知道为什么......请帮帮我。

4

1 回答 1

1

我测试了你的zipFilesAndDownload功能,它运行良好。<?php因此,首先您应该检查您的脚本,是否在开始标记之前没有发送任何字符或空格。

如果您的脚本在 CMS 中运行,您还应该清除所有输出缓冲区:(while (@ob_end_clean());如果 gzip 标头已发送,则还要再次打开 gz 压缩ob_start('ob_gzhandler');

您还可以检查是否正确设置了 $file_path 并且所有文件都存在,例如:

$file_path='resume/';
if (!file_exists($file_path) || !is_dir($file_path)) {
    die("Invalid directory $file_path in ".getcwd());
}
// you can test the existence of your problematic files:
foreach ($file_names as $file) {
    if (!file_exists($file_path.$file)) {
        echo "$file not found.";
    } else {
        echo "$file is ok.";
    }
}
exit;
// end of test
zipFilesAndDownload($file_names,$archive_file_name,$file_path);

在 Windows 中,UTF-16/UTF-8/国际字符编码也存在问题,请参见此处:PHP检测文件系统编码如何在 PHP 中使用文件系统函数,使用 UTF-8 字符串?.

于 2012-07-14T18:51:39.750 回答