编辑:问题在下面回答。如果您想像我所做的那样压缩目录/文件夹,请参阅:如何使用 PHP 压缩整个文件夹
我有一个带有计时器的应用程序,可以从我的服务器自动下载 ZIP 文件。
但是 ZIP 文件每天都在更改。
当有人使用该应用程序时,应用程序用户将收到“550 文件不可用”错误,因为 ZIP 文件被删除并再次添加(这是因为应用程序计时器每 900 毫秒执行一次)。
因此,不是删除 ZIP 文件并使用新数据重新创建它,而是如何在不重新创建 ZIP 文件的情况下添加新数据?
目前我使用这个:
$zip = new ZipArchive;
// Get real path for our folder
$rootPath = realpath('../files_to_be_in_zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('../zouch.zip', 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)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
Run Code Online (Sandbox Code Playgroud)
这段代码获取files_to_be_in_zip文件夹的内容并用它重新创建“zouch.zip”文件。
是的,我知道新的数据全路径......它是 $recentlyCreatedFile
编辑:我在http://php.net/manual/en/ziparchive.addfile.php上找到了这段代码
<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->addFile('/path/to/index.txt', 'newname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
Run Code Online (Sandbox Code Playgroud)
但我也想在现有的 ZIP 中创建一个目录。
有什么帮助吗?
谢谢!
当您打开 zip 时,您在第二个参数中指定它是新创建的还是覆盖的。删除第二个参数应该会使您的脚本按原样工作。以下是您已实施所需编辑的代码。
$zip = new ZipArchive;
// Get real path for our folder
$rootPath = realpath('../files_to_be_in_zip');
$zip->open('../zouch.zip');
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file){
// Skip directories (they would be added automatically)
if (!$file->isDir()){
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
Run Code Online (Sandbox Code Playgroud)
但是,如果您的数据已经在 ZIP 文件中,但将来需要替换,那么您必须使用 ZipArchive::OVERWRITE
$zip->open('../zouch.zip', ZipArchive::OVERWRITE);
Run Code Online (Sandbox Code Playgroud)