插件开发完毕后,发布需要对插件进行打包,往往通过手动打包非常不方便,于是想到用php自动的相关文件进行zip压缩打包,下面示例是通过ZipArchive类完成的。
本例是zip压缩重点是,被压缩的文件按照其目录结构压缩进zip压缩包。
重要说明:
1. 同时把不同目录按照其目录结构压缩至同一zip文件,$zipFile内容目录结构不变,$folderPaths此时为数组 ['app/data/','public/data/'];数组内为不同目录路径
2. 把单个目录进行压缩,且压缩包内的目录保持其结构不变,$folderPaths此时为路径字符串'app/data/';
3. root_path() 为thinkphp的root绝对路径,此处为压缩包内保持目录结构相对路径的关键。
/**
* 保持目录结构的压缩方法
* @param string $zipFile
* @param $folderPaths
* @return void
*/
public static function dirZip(string $zipFile, $folderPaths)
{
//1. $folderPaths 路径为数组
// 初始化zip对象
$zip = new \ZipArchive();
//打开压缩文件
$zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
if(is_array($folderPaths)) {
foreach($folderPaths as $folderPath) {
// 被压缩文件绝对路径
$rootPath = realpath($folderPath);
// Create recursive directory iterator
//获取所有文件数组SplFileInfo[] $files
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($rootPath),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
//要跳过所有子目录
if (!$file->isDir()) {
// 真实文件路径
$filePath = $file->getRealPath();
// zip文件的相对路径
$relativePath = str_replace(root_path(), '', $filePath);
//添加文件到压缩包
$zip->addFile($filePath, $relativePath);
}
}
}
} else {
// 2. $folderPaths 路径为string
// 被压缩文件绝对路径
$rootPath = realpath($folderPaths);
// Create recursive directory iterator
//获取所有文件数组SplFileInfo[] $files
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($rootPath),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
//要跳过所有子目录
if (!$file->isDir()) {
// 要压缩的文件路径
$filePath = $file->getRealPath();
// zip目录内文件的相对路径
$relativePath = str_replace(root_path(), '', $filePath);
//添加文件到压缩包
$zip->addFile($filePath, $relativePath);
}
}
}
$zip->close();
}
还没有内容