open($filename,ZipArchive::CREATE);" and use "$zip->addFile($path,basename($path));" to add files to the compressed package. Compress the file.">
Compress a file
We generate a compressed package from a file.
open($filename,ZipArchive::CREATE); //打开压缩包 $zip->addFile($path,basename($path)); //向压缩包中添加文件 $zip->close(); //关闭压缩包
The above code compresses the c:/wamp/www/log.txt file into test.zip and saves it in the current directory.
Related recommendations: "php Getting Started Tutorial"
Compress multiple files
Compressing multiple files is actually addFile Execution multiple times can be achieved by traversing the array.
open($filename,ZipArchive::CREATE); //打开压缩包 foreach($fileList as $file){ $zip->addFile($file,basename($file)); //向压缩包中添加文件 } $zip->close(); //关闭压缩包
Compress a directory
addFile($path."/".$filename); } } } @closedir($path); } $zip=new ZipArchive(); if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){ addFileToZip('rsa/', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 $zip->close(); //关闭处理的zip文件 }
Compress and download the zip package
In my case, we need to provide it after packaging Download and then delete the compressed package.
can be divided into the following steps:
(1) Determine whether the given path is a folder or a file. The folder also needs to be traversed to add files.
(2) Set the relevant file header and use the readfile function to provide downloading.
(3) Use the unlink function to delete the compressed package.
addFile($path."/".$filename); } } } @closedir($path); } $zip=new ZipArchive(); if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){ $path = 'rsa/'; if(is_dir($path)){ //给出文件夹,打包文件夹 addFileToZip($path, $zip); }else if(is_array($path)){ //以数组形式给出文件路径 foreach($path as $file){ $zip->addFile($file); } }else{ //只给出一个文件 $zip->addFile($path); } $zip->close(); //关闭处理的zip文件 }
The above is the detailed content of How to compress files in php. For more information, please follow other related articles on the PHP Chinese website!