В php иногда нам нужно использовать сжатый файл , сжатый файл может сэкономить место на диске; а сжатый файл меньше, удобен для передачи по сети, высокая эффективность, давайте узнаем о операциях, связанных со сжатием и декомпрессией PHP.
В PHP есть класс ZipArchive, который предназначен для сжатия и распаковки файлов
Следующие методы в основном используются в классе ZipArchive:
1:открыть (открыть zip-файл)
$zip = new \ZipArchive;
$zip->open('test_new.zip', \ZipArchive::CREATE)Первый параметр: сжатый файл пакета для открытия
Второй параметр:
ZIPARCHIVE:: ПЕРЕЗАПИСЬ всегда создает новый файл и перезаписывает указанный zip-файл, если он существует.
ZIPARCHIVE:: СОЗДАТЬ Если указанный zip-файл не существует, создайте новый
ZIP-АРХИВ:: EXCEL сообщит об ошибке, если указанный zip-файл существует
ZIPARCHIVE:: CHECKCONS выполняет другие тесты на соответствие указанным молниям
2: добавить файл (добавьте указанный файл в сжатый пакет)
// Add the test.txt file to the compressed package
$zip - > addFile ('test. txt'); the second parameter can rename the file3: addEmptyDir (добавьте указанный пустой каталог в сжатый пакет)
// Add an empty directory to zip
$zip->addEmptyDir ('newdir');4: addFromString
// Add the new.txt file with the specified content to the zip file
$zip - > addFromString ('new.txt','text to be added to the new.txt file');5: извлечь В (извлечь сжатый пакет в указанный каталог)
$zip->extractTo('test');
6: Индекс getName (возвращает имя файла на основе индекса)
$zip - > getNameIndex (0); // Returns the name of the file indexed to 0 in the compressed package
7: GetStream (Получение текстового потока файла на основе имени файла при сжатии)
$zip->getStream('hello.txt');
8: переименуйте индекс (Измените имя файла в сжатом файле в соответствии с индексом в сжатом файле (начиная с 0)
/ Modify the first file in the compressed file to newname.txt $zip->renameIndex(0,'newname.txt');
9: переименовать имя (Изменить имя файла в сжатом файле в соответствии с именем файла в сжатом файле)
// Modify word.txt in the compressed file to newword.txt
$zip->renameName('word.txt','newword.txt');10:удалить индекс (Удалить файлы в сжатых файлах в соответствии с индексом в сжатых файлах)
/ Delete the first file in the compressed file $zip->deleteIndex (0);
11: удалить имя (удалить файлы в соответствии с именем файла в сжатом файле)
// Delete word.txt from the compressed file
$zip->deleteName('word.txt');Вот некоторые распространенные методы Zip-архива, и вот несколько простых примеров
Первый: Создайте сжатый пакет
$zip = new \ZipArchive;
if ($zip->open('test_new.zip', \ZipArchive::CREATE) === true)
{
// Add the specified file to zip
$zip->addFile('test.txt');
// The test.txt file is added to zip and renamed newfile.txt
$zip->addFile('test.txt', 'newfile.txt');
// Add the test.txt file to the test folder in the zip file
$zip->addFile('test.txt', 'test/newfile.txt');
// Add an empty directory to zip
$zip->addEmptyDir ('test');
// Add the new.txt file with the specified content to the zip file
$zip - > addFromString ('new.txt','text to be added to the new.txt file');
// Add new.txt with the specified content to the test folder in the zip file
$zip - > addFromString ('test/new.txt','text to be added to the new.txt file');
// Add all files in the images directory to zip
if ($handle = opendir('images')){
// Add all files in the directory
while (false !== ($entry = readdir($handle))){
if ($entry != "." && $entry != ".." && !is_dir('images/' . $entry)){
$zip->addFile('images/' . $entry);
}
}
closedir($handle);
}
// Close the zip file
$zip->close();
}2. Получите информацию о файле сжатого пакета и распакуйте указанный сжатый пакет
$zip = new \ZipArchive;
if ($zip->open('test_new.zip') === true) {
// Get the name of the file with index 0
var_dump($zip->getNameIndex(0));
// Unzip the compressed package file into the test directory
$zip->extractTo('test');
// Get the text stream of the compressed package specified file
$stream = $zip->getStream('test.txt');
// Close the zip file
$zip->close();
STR = stream_get_contents ($stream); // Note the text encoding obtained here
var_dump($str);
}3. Измените имя файла указанного файла в сжатом пакете и удалите указанный файл в сжатом пакете
$zip = new \ZipArchive;
if ($zip->open('test_new.zip') === true) {
// Modify the file with index 0 in the compressed file to newname.txt
$zip->renameIndex(0,'newname.txt');
// Modify the new.txt in the compressed file to newword.txt
$zip->renameName('new.txt','newword.txt');
// Delete files with index 0 in compressed files
$zip->deleteIndex(0);
// Delete test.png from compressed files
$zip->deleteName('test.png');
// Close the zip file
$zip->close();
}Выше приведено все содержание этой статьи. Я надеюсь, что это будет полезно для изучения каждого, и я надеюсь, что вы будете больше поддерживать разработчика.