This article mainly introduces the functions of ZipArchive function in php. Interested friends can refer to it. I hope it will be helpful to everyone.
1. Unzip the zip file
$zip=new ZipArchive;//新建一个ZipArchive的对象 if($zip->open('test.zip')===TRUE){ $zip->extractTo('images');//假设解压缩到在当前路径下images文件夹内 $zip->close();//关闭处理的zip文件 }
2. Compress the file into a zip file
$zip=new ZipArchive; if($zip->open('test.zip',ZipArchive::OVERWRITE)===TRUE){ $zip->addFile('image.txt');//假设加入的文件名是image.txt,在当前路径下 $zip->close(); }
3 , append the file content to the zip file
$zip=new ZipArchive; $res=$zip->open('test.zip',ZipArchive::CREATE); if($res===TRUE){ $zip->addFromString('test.txt','file content goes here'); $zip->close(); echo 'ok'; }else{ echo 'failed'; }
4. Pack the folder into a zip file
function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定。 while(($filename=readdir($handler))!==false){ if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..',不要对他们进行操作 if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归 addFileToZip($path."/".$filename, $zip); }else{ //将文件加入zip对象 $zip->addFile($path."/".$filename); } } } @closedir($path); } $zip=new ZipArchive(); if($zip->open('images.zip', ZipArchive::OVERWRITE)=== TRUE){ addFileToZip('images/', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 $zip->close(); //关闭处理的zip文件 }
Summary: The above is the entire content of this article , I hope it can be helpful to everyone’s study.
Related recommendations:
PHP methods and examples for implementing browser inspection classes
About PHP for keywords in text content Methods for red-coding processing
PHP methods and examples of generating MYSQL statement classes through parameters
The above is the detailed content of Function of ZipArchive function in php. For more information, please follow other related articles on the PHP Chinese website!