原本地址:https://blog.yayuanzi.com/9600.html
找了好久,終於找到個博客有說這個的,具體的請看下面的代碼
PHP中有個解壓縮的擴展庫ZipArchive(),可以用來實現解壓縮的功能。當我使用ZipArchive做一個壓縮文件夾及子文件夾的功能時卻遇到一個問題,ZipArchive不能直接操作文件夾,也就是ZipArchive不能直接壓縮文件夾。幸好,ZipArchive提供了兩個方法addEmptyDir()和addFromString(),我們可以通過這兩個方法來實現文件夾的壓縮。
解決思路:遍歷文件夾,如果是子文件夾,使用addEmptyDir()創建一個空文件夾;如果是子文件,使用addFromString()以字符串的形式將文件添加到對應的目錄。
/**
* 壓縮文件夾及文件
* @param type $source 需要壓縮的文件夾/文件路徑
* @param type $destination 壓縮後的保存地址
* @param type $folder 文件夾前綴,保存時需要去掉的父級文件夾
* @return boolean
*/
function Zip($source, $destination,$folder='')
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', $source);
$folder = str_replace('\\', '/', $folder);
if (is_dir($source) === true) {
// $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
$files = new \RecursiveDirectoryIterator($source,\RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
// $file = realpath($file);
if (is_dir($file) === true) {
$zip->addEmptyDir(str_replace($folder . '/', '', $file . '/'));
} else if (is_file($file) === true) {
$zip->addFromString(str_replace($folder . '/', '', $file), file_get_contents($file));
}
}
} else if (is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}