美文网首页
ZipArchive压缩文件夹[转载]

ZipArchive压缩文件夹[转载]

作者: willeny | 来源:发表于2018-07-27 21:17 被阅读0次

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

}

相关文章

网友评论

      本文标题:ZipArchive压缩文件夹[转载]

      本文链接:https://www.haomeiwen.com/subject/gaxnmftx.html