ZipArchive压缩文件夹[转载]

原本地址: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();

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值