PHP的ZipArchive类允许您批量操作ZIP文件。以下是一些常见的批量操作示例:
<?php
$zip = new ZipArchive;
$zipFilename = 'example.zip';
if ($zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
exit("无法打开 <$zipFilename>\n");
}
$filesToAdd = array('file1.txt', 'file2.txt', 'file3.txt');
foreach ($filesToAdd as $file) {
$zip->addFile($file);
}
$zip->close();
?>
<?php
$zipFilename = 'example.zip';
$destination = './extract-folder/';
if (!is_dir($destination)) {
mkdir($destination);
}
$zip = new ZipArchive;
if ($zip->open($zipFilename) === TRUE) {
$zip->extractTo($destination);
$zip->close();
echo "成功提取 <$zipFilename>\n";
} else {
echo "无法打开 <$zipFilename>\n";
}
?>
<?php
$zipFilename = 'example.zip';
$zip = new ZipArchive;
if ($zip->open($zipFilename) === TRUE) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
if ($fileinfo['extension'] == 'txt') {
echo "文件名: {$filename}\n";
}
}
$zip->close();
} else {
echo "无法打开 <$zipFilename>\n";
}
?>
<?php
$zipFilename = 'example.zip';
$filesToRemove = array('file2.txt', 'file3.txt');
$zip = new ZipArchive;
if ($zip->open($zipFilename) === TRUE) {
foreach ($filesToRemove as $file) {
$index = $zip->getLocationIndex($file);
if ($index !== false) {
$zip->deleteIndex($index);
}
}
$zip->close();
echo "成功从 <$zipFilename> 中删除文件\n";
} else {
echo "无法打开 <$zipFilename>\n";
}
?>
这些示例展示了如何使用PHP的ZipArchive类执行常见的批量操作。您可以根据需要修改这些示例以满足您的具体需求。