将 zip 中的文件解压缩到文件夹的根目录? [英] Extract files in a zip to root of a folder?

查看:100
本文介绍了将 zip 中的文件解压缩到文件夹的根目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 zip 文件上传到服务器用于自动提取.

I have a zip file uploaded to server for automated extract.

zip 文件结构如下:

the zip file construction is like this:

/zip_file.zip/folder1/image1.jpg
/zip_file.zip/folder1/image2.jpg
/zip_file.zip/folder1/image3.jpg

目前我有这个功能来提取所有扩展名为 jpg 的文件:

Currently I have this function to extract all files that have extension of jpg:

$zip = new ZipArchive();
    if( $zip->open($file_path) ){
        $files = array();
        for( $i = 0; $i < $zip->numFiles; $i++){
            $entry = $zip->statIndex($i);
            // is it an image?  
            if( $entry['size'] > 0 && preg_match('#\.(jpg)$#i', $entry['name'] ) ){
                $f_extract = $zip->getNameIndex($i);
                $files[] = $f_extract;
            }
        }
        if ($zip->extractTo($dir_name, $files) === TRUE) {
        } else {
            return FALSE;
        }

        $zip->close();
    }

但是通过使用函数extractTo,它将提取到myFolder 为ff:

But by using the function extractTo, it will extract to myFolder as ff:

/myFolder/folder1/image1.jpg
/myFolder/folder1/image2.jpg
/myFolder/folder1/image3.jpg

有什么办法可以把folder1中的文件解压到myFolder的根目录下吗?

Is there any way to extract the files in folder1 to the root of myFolder?

理想:

/myFolder/image1.jpg
/myFolder/image2.jpg
/myFolder/image3.jpg

PS:万一文件名冲突,我只需要不提取或覆盖文件.

PS: incase of conflict file name I only need to not extract or overwrite the file.

推荐答案

改用这个小代码片段.它删除了每个文件的文件名前面的文件夹结构,以便存档的全部内容基本上被提取到一个文件夹中.

Use this little code snippet instead. It removes the folder structure in front of the filename for each file so that the whole content of the archive is basically extracted to one folder.

<?php
$path = "zip_file.zip";

$zip = new ZipArchive();
if ($zip->open($path) === true) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $fileinfo = pathinfo($filename);
        copy("zip://".$path."#".$filename, "/myDestFolder/".$fileinfo['basename']);
    }                  
    $zip->close();                  
}
?>

这篇关于将 zip 中的文件解压缩到文件夹的根目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆