在将这篇文章标记为重复之前,请注意,我已经在 SO 上搜索过答案,并且到目前为止我发现的一次答案(如下所列)并不完全是我一直在寻找的答案。
- 如何在 PHP 中[递归地]压缩目录? https://stackoverflow.com/questions/1334613/how-to-recursively-zip-a-directory-in-php
- 使用 zipArchive addFile() 不会将图像添加到 zip https://stackoverflow.com/questions/5422983/using-ziparchive-addfile-will-not-add-image-to-zip
- ZipArchive - addFile 不起作用 https://stackoverflow.com/questions/6289456/ziparchive-addfile-wont-work
这些只是我看过的一些。
我的问题是这样的:我不能使用 addFromString,我have要使用 addFile,这是任务的要求。
我已经尝试了几种方法,这是我当前的迭代:
public function getZippedFiles($path)
{
$real_path = WEBROOT_PATH.$path;
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($real_path), RecursiveIteratorIterator::LEAVES_ONLY);
//# create a temp file & open it
$tmp_file = tempnam($real_path,'');
$zip_file = preg_replace('"\.tmp$"', '.zip', $tmp_file);
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE);
foreach ($files as $name=>$file)
{
error_log(print_r($name, true));
error_log(print_r($file, true));
if ( ($file == ".") || ($file == "..") )
{
continue;
}
$file_path = $file->getRealPath();
$zip->addFile($file_path);
}
$zip->close();
}
当我尝试打开生成的文件时,我被告知“Windows 无法打开该文件夹。压缩(zipped)文件夹''无效。”
我已经成功使用 addFromString 完成了任务,如下所示:
$file_path = WEBROOT_PATH.$path;
$files = array();
if (is_dir($file_path) == true)
{
if ($handle = opendir($file_path))
{
while (($file = readdir($handle)) !== false)
{
if (is_dir($file_path.$file) == false)
{
$files[] = $file_path."\\".$file;
}
}
//# create new zip opbject
$zip = new ZipArchive();
//# create a temp file & open it
$tmp_file = tempnam($file_path,'');
$zip_file = preg_replace('"\.tmp$"', '.zip', $tmp_file);
$zip->open($zip_file, ZipArchive::CREATE);
//# loop through each file
foreach($files as $file){
//# download file
$download_file = file_get_contents($file);
//#add it to the zip
$zip->addFromString(basename($file),$download_file);
}
//# close zip
$zip->close();
}
}
}
上面的内容大部分是直接从我在某处看到的一些示例代码中复制的。如果有人能指出我一个好的方向,我将非常感激!
***** 更新 *****
我在关闭周围添加了一个 if ,如下所示:
if (!$zip->close()) {
echo "failed writing zip to archive";
}
该消息得到回显,所以显然问题就在那里。我还检查过以确保$zip->open()
有效,并且我已经确认它可以毫无问题地打开它。