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類執(zhí)行常見的批量操作。您可以根據(jù)需要修改這些示例以滿足您的具體需求。