我正在尝试从我的应用程序(Laravel 5.8)上的文件夹下载 zip,它可以工作,但它们会跳过所有空文件夹,而我需要将它们放在 zip 中。
我已经尝试过 Composer 的 ZipArchive (php) 和 chumper/zipper。
知道我该怎么做吗?
这是一个 Linux 服务器,运行 MySQL 5、PHP 7.2 和 Apache2。
$files = glob($folder_path);
\Zipper::make($folder_path.'/'.$folder_main_name.'.zip')->add($files)->close();
这个库只接受 glob,但是如果你有任何有效的解决方案,我可以轻松放弃它。
最佳答案
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file)
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
if (!$file->isDir())
{
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}else {
if($relativePath !== false)
$zip->addEmptyDir($relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
嗨。我修改了之前的答案,现在我得到了包含空文件夹的 zip 文件。我希望这会有所帮助。
关于php - 如何在 PHP 中压缩整个文件夹,甚至是空文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55927020/