php压缩与归档扩展-zip基本用法
发表于:2020-05-25 16:21:51浏览:58次
简介
此扩展可以让你透明地读写ZIP压缩文档以及它们里面的文件。
安装
编译安装
编译 PHP 时用 --enable-zip 配置选项来提供 zip 支持。下载安装包安装
# libzip 依赖,php7.4版本中要求 libzip >=0.11 wget https://nih.at/libzip/libzip-1.2.0.tar.gz tar -zxvf libzip-1.2.0.tar.gz cd libzip-1.2.0 sudo ./configure sudo make sudo make installphp原包中安装
cd php-7.4.4/ext/zip /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config make make install# 安装zip包 wget https://pecl.php.net/get/zip-1.15.5.tgz tar -zxvf zip-1.15.5.tgz cd zip-1.15.5/ phpize ./configure --with-php-config=/usr/local/php/bin/php-config make make install将zip加入php.ini
sudo vim /etc/php5/fpm/conf.d/zip.ini[zip] extension=zip.so重启php
编码
多个单个文件打包
# 打包临时文件夹,请设置可写 $tmp_dir = "/tmp/zip_dir"; # 打包zip的文件名 $zip_file_name = "zip_file_" . time(); # zip的绝对路径 $zip_file = $tmp_dir . "/" . $zip_file_name . ".zip"; # 开始打包 $zip = new ZipArchive(); $res = $zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE); if($res === true) { $zip_file_arr = array( 'a.txt' => "/tmp/file_list/a.txt", 'b.txt' => "/tmp/file_list/b.txt", ); # $key = 文件名 # $value = 文件路径 foreach ($zip_file_arr as $key => $value) { $zip->addFile($value, $key); } # 关闭写 $zip->close(); }else{ exit("zip open fail! code: " . $res); }文件夹打包
# 打包临时文件夹,请设置可写 $tmp_dir = "/tmp/zip_dir"; # 打包的文件夹及文件夹下的文件 $path = "/tmp/file_list"; # zip的绝对路径 $zip_file = $tmp_dir . "/" . $zip_file_name . ".zip"; # 开始打包 $zip = new ZipArchive(); $res = $zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE); if($res === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($files as $name => $file) { // Skip directories (they would be added automatically) if (!$file->isDir()) { // Get real and relative path for current file $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($path) + 1); // Add current file to archive $zip->addFile($filePath, $relativePath); } } # 关闭写 $zip->close(); }else{ exit("zip open fail! code: " . $res); }如果要提交http下载的话,可使用如下代码
# http下载 $fp_zip = fopen('php://output', 'a'); header("Content-type:application/octet-stream"); header("Content-Disposition:attachment;filename=" . $zip_file_name . ".zip"); header("Accept-ranges:bytes"); fwrite($fp_zip, file_get_contents($zip_file)); fclose($fp_zip); // 删除zip文件 unlink($zip_file);

