仅从带有 php 的 zip 文件中检索文件夹名称? [英] retrieve folders names only from a zip file with php?

查看:25
本文介绍了仅从带有 php 的 zip 文件中检索文件夹名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 zip 文件中检索文件夹名称.我写了这个简单的函数:

I'm trying to retrieve folders name from a zip file. I wrote this simple function :

<?php
class zipadmin{
    private $filename ;
    private $folder ;
    public function __construct($filename,$folder){
        $this->zip = new ZipArchive;
        $this->file = $filename ;
        $this->folder = $folder ;
    }
    public function listzip(){
    if ($this->zip->open($this->file) == TRUE) {
        $info = $this->zip->statIndex(0);
        $output = str_replace('/','',$info['name']);
        return $output;
        }
    }
}

问题是,如果 zip 文件夹包含文件夹中未包含的其他文件,它会返回所有文件名.我需要它只返回文件夹名称并丢弃任何文件名.

Problem that if the zip folder contain other files which is not included inside the folders it return all the files names. I need it to return folders names only and discard any files name.

推荐答案

您可以尝试检查 $info['crc'] 何时等于 0.

You can try to check when $info['crc'] equals to zero.

class zipadmin{

  private $file;
  private $folder;
  private $zip;

  public function __construct($filename, $folder) {
    $this->zip = new ZipArchive;
    $this->file = $filename ;
    $this->folder = $folder ;
    }

  public function listzip() {
    $res = false;
    if ($this->zip->open($this->folder . $this->file) == TRUE) {
      $i = 0;
      while ($info = $this->zip->statIndex($i)) {
        if ($info['crc'] == 0 && preg_match('#^[^/]*?/$#', $info['name']))
          $res[] = preg_replace('#^([^/]*?)/$#', '$1', $info['name']);
        $i++;
        }
      }
    return $res;
    }

}

使用示例:

$z = new zipadmin('test.zip', './'); // test.zip in my example is in same folder
print_r($z->listzip());

输出(仅限根目录数组):

Array
(
    [0] => folder1
    [1] => folder2
    [2] => folder3
    [3] => folder4
)

在我的 test.zip 存档中,我在存档的根目录和 4 个目录 folder1folder2folder3 中有几个文件folder4 里面有一些文件和子目录.针对没有文件夹的存档运行方法返回布尔值 false.

In my test.zip archive I have few files in root directory of archive and 4 directories folder1, folder2, folder3 and folder4with some files and sub-directories inside them. Running method against archive with no folders returns boolean false.

更新:

  • 修复了正则表达式模式以匹配第一个斜杠 / 之前的所有内容.
  • Fixed regex pattern to match everything before first slash /.

这篇关于仅从带有 php 的 zip 文件中检索文件夹名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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