Function of ZipArchive function in php

墨辰丷
Release: 2023-03-30 09:22:02
Original
1676 people have browsed it

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文件 
}
Copy after login

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(); 
}
Copy after login

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'; 
}
Copy after login

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文件 
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!