php 压缩文件夹
Posted _大可乐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 压缩文件夹相关的知识,希望对你有一定的参考价值。
php 压缩文件夹
例子来源于php官方文档。
<?php
{
/**
* Add files and sub-directories in a folder to zip file.
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path.
*/
private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
$handle = opendir($folder);
while (false !== $f = readdir($handle)) {
if ($f != ‘.‘ && $f != ‘..‘) {
$filePath = "$folder/$f";
// 去除文件前缀地址
$localPath = substr($filePath, $exclusiveLength);
if (is_file($filePath)) {
//第一个参数是添加文件的绝对路径,第二是参数是添加到压缩包的文件名称。
$zipFile->addFile($filePath, $localPath);
} elseif (is_dir($filePath)) {
// 如果是文件夹递归添加。
$zipFile->addEmptyDir($localPath);
self::folderToZip($filePath, $zipFile, $exclusiveLength);
}
}
}
closedir($handle);
}
/**
* Zip a folder (include itself).
* Usage:
* HZip::zipDir(‘/path/to/sourceDir‘, ‘/path/to/out.zip‘);
*
* @param string $sourcePath Path of directory to be zip.
* @param string $outZipPath Path of output zip file.
*/
public static function zipDir($sourcePath, $outZipPath)
{
$pathInfo = pathInfo($sourcePath);
$parentPath = $pathInfo[‘dirname‘];
$dirName = $pathInfo[‘basename‘];
$z = new ZipArchive();
$z->open($outZipPath, ZIPARCHIVE::CREATE);
$z->addEmptyDir($dirName);
self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
$z->close();
}
}
以上是关于php 压缩文件夹的主要内容,如果未能解决你的问题,请参考以下文章