TAY
笔记 · · 阅读 199

php 读取zip压缩包目录和文件 tree

function treeToHtml($tree) {
    $html = '<ul>';
    // 先输出文件夹
    foreach ($tree as $name => $subtree) {
        if (!empty($name) && empty(pathinfo($name, PATHINFO_EXTENSION))) {
            $html .= '<li';
            if (!empty($subtree)) {
                $html .= '   data-jstree=\'{"type":"folder"}\'';
            }
            $html .= '>' . htmlentities($name);
            if (!empty($subtree)) {
                $html .= treeToHtml($subtree);
            }
            $html .= '</li>';
        }
    }

        // 再输出文件
        foreach ($tree as $name => $subtree) {
            if (!empty($name) && !empty(pathinfo($name, PATHINFO_EXTENSION))) {
                $ext = pathinfo($name, PATHINFO_EXTENSION);
                $html .= '<li';
                if (!empty($subtree)) {
                    $html .= '  data-jstree=\'{"type":"folder"}\'';
                }
                $html .= ' data-jstree=\'{"type":"'.$ext.'"}\'';
                $html .= '>' . htmlentities($name);
                if (!empty($subtree)) {
                    $html .= treeToHtml($subtree);
                }
                $html .= '</li>';
            }
        }

    $html .= '</ul>';
    return $html;
 }
$zip = new \ZipArchive();
$file = public_path()."/1.zip";
if ($zip->open($file) === true) {
       // 初始化文件树结构
        $tree = [];
        for ($i = 0; $i < $zip->numFiles; $i++) {
        // 获取文件名
        $filename = $zip->getNameIndex($i);
        // 分割路径为数组
        $path = explode('/', $filename);
        $node = &$tree;
        foreach ($path as $dir) {
            if (!isset($node[$dir])) {
                //$node[$dir] = [];
            }
            $node = &$node[$dir];
        }
    }
}
$zip->close();
//print_r($tree);
echo treeToHtml($tree);
目录