Written by PHP editor Baicao, this article will unveil the mystery of PHP ZipArchive extension and teach you how to easily manage compressed files. ZipArchive is a powerful compressed file processing extension in PHP that can be used to create, open, extract and add content to ZIP files. Through this article, you will learn how to use the ZipArchive extension to perform file compression and decompression operations, making your file management more efficient and convenient. Come explore with us!
Create compressed file
To create a new compressed file, you can use ZipArchive::open()
Function:
$zip = new ZipArchive(); if ($zip->open("my_archive.zip", ZipArchive::CREATE) === TRUE) { // 将文件添加到压缩文件 $zip->addFile("file1.txt", "new_file1.txt"); // 关闭压缩文件 $zip->close(); }
Extract compressed files
To extract files from a compressed file, you can use ZipArchive::extractTo()
Function:
$zip = new ZipArchive(); if ($zip->open("my_archive.zip") === TRUE) { // 将压缩文件中的内容提取到指定的目录 $zip->extractTo("extracted_files"); // 关闭压缩文件 $zip->close(); }
Add files to compressed file
To add files to an existing archive, you can use ZipArchive::addFile()
Function:
$zip = new ZipArchive(); if ($zip->open("my_archive.zip") === TRUE) { // 将文件添加到压缩文件 $zip->addFile("file2.txt", "new_file2.txt"); // 关闭压缩文件 $zip->close(); }
Delete files to compressed files
To delete files from a compressed file, you can use ZipArchive::deleteIndex()
Function:
$zip = new ZipArchive(); if ($zip->open("my_archive.zip") === TRUE) { // 删除压缩文件中的第一个文件 $zip->deleteIndex(0); // 关闭压缩文件 $zip->close(); }
Traverse compressed files
To traverse the file information in the compressed file, you can use ZipArchive::getStream()
Function:
$zip = new ZipArchive(); if ($zip->open("my_archive.zip") === TRUE) { for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); echo $stat["name"] . php_EOL; } // 关闭压缩文件 $zip->close(); }
Set compression level
To set the compression level when compressing files, you can use ZipArchive::setCompress<strong class="keylink">io</strong>nIndex()
Function:
$zip = new ZipArchive(); if ($zip->open("my_archive.zip", ZipArchive::CREATE) === TRUE) { // 将压缩级别设置为最高 $zip->setCompressionIndex(9); // 将文件添加到压缩文件 $zip->addFile("file1.txt", "new_file1.txt"); // 关闭压缩文件 $zip->close(); }
in conclusion
PHP ZipArchive extension provides a comprehensive set of functions to manage compressed files. Whether you need to create, extract, add or delete files from a compressed archive, it provides a fast and efficient solution. By leveraging the power of this extension, you can easily automate your file management tasks and increase your work efficiency.
The above is the detailed content of PHP ZipArchive Extension Revealed: Easily Manage Compressed Files. For more information, please follow other related articles on the PHP Chinese website!