gpt4 book ai didi

php - 将文件添加到现有 ZIP 文件

转载 作者:可可西里 更新时间:2023-11-01 01:13:40 25 4
gpt4 key购买 nike

编辑:下面回答了这个问题。如果您想像我一样压缩目录/文件夹,请参阅:How to zip a whole folder using 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();

此代码获取 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';
}
?>

但我也想在现有的 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();

但是,如果您的数据已经在 ZIP 文件中但将来需要替换,那么您必须使用 ZipArchive::OVERWRITE

$zip->open('../zouch.zip', ZipArchive::OVERWRITE);

关于php - 将文件添加到现有 ZIP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45926215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com