在没有路径结构的另一个目录中从PHP压缩文件

时间:2012-12-25 17:58:34

标签: php zip relative-path

我正在尝试在另一个目录中压缩两个文件,而不会压缩文件夹层次结构。

按下按钮触发事件,这会导致Javascript使用AJAX向PHP发送信息。 PHP调用Perl脚本(利用Perl的XLSX编写器模块以及PHP类型很糟糕,但我离题了......),它将文件放在层次结构中的几个文件夹中。相关代码如下所示。

system("createFiles.pl -ids ${rows} -test ${test} -path ${path}",$retVal);

`zip ${path}/{$test}_both.zip ${path}/${test}.csv ${path}/${test}.xlsx`;
`zip ${path}/{$test}_csv.zip  ${path}/${test}.csv`;

问题是zip文件具有${path}层次结构,必须在文件显示之前导航,如下所示:

Zip with hierarchy

我尝试过这样做(在每个zip命令之前使用cd):

system("createFiles.pl -ids ${rows} -test ${test} -path ${path}",$retVal);

`cd ${path}; zip {$test}_both.zip ${test}.csv ${test}.xlsx`;
`cd ${path}; zip {$test}_csv.zip  ${test}.csv`;

它有效,但它似乎是一个黑客。还有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

如果您使用PHP 5> = 5.2.0,则可以使用ZipArchive类。然后,您可以使用完整路径作为源文件名,只使用文件名作为目标名称。像这样:

$zip = new ZipArchive;
if($zip->open("{$test}_both.zip", ZIPARCHIVE::OVERWRITE) === true) {
    // Add the files here with full path as source, short name as target
    $zip->addFile("${path}/${test}.csv", "${test}.csv");
    $zip->addFile("${path}/${test}.xlsx", "${test}.xlsx");
    $zip->close();
} else {
    die("Zip creation failed.");
}

// Same for the second archive
$zip2 = new ZipArchive;
if($zip2->open("{$test}_csv.zip", ZIPARCHIVE::OVERWRITE) === true) {
    // Add the file here with full path as source, short name as target
    $zip2->addFile("${path}/${test}.csv", "${test}.csv");
    $zip2->close();
} else {
    die("Zip creation failed.");
}

答案 1 :(得分:1)

Oldskool的ZipArchive答案很好。我使用了ZipArchive并且它有效。但是,我推荐使用PclZip,因为它更通用(例如,允许在没有压缩的情况下进行压缩,如果您正在压缩已经压缩的图像,则更快)。 PclZip支持PCLZIP_OPT_REMOVE_ALL_PATH选项删除所有文件路径。 e.g。

$zip = new PclZip("$path/{$test}_both.zip");
$files = array("$path/$test.csv", "$path/$test.xlsx");

// create the Zip archive, without paths or compression (images are already compressed)
$properties = $zip->create($files, PCLZIP_OPT_REMOVE_ALL_PATH);
if (!is_array($properties)) {
    die($zip->errorInfo(true));
}