2

PHPを使用して、1つの特定のフォルダー内のすべてのフォルダーとファイルを一覧表示しようとしています。以下のコードを使用して、すべてのファイルとフォルダーを1つの長いリストにリストすることができました。今私が本当にやろうとしているのは、HTML / jqueryを使用して、ディレクトリの結果を横に+マークが付いたフォルダーとして表示して展開できるようにすることですが、結果をフォーマットする方法がわかりません。それを行うためのPHP。

 include('include/class.dirlist.php');
 $resources = "/Inetpub/companyweb/resources";
 $dir = getDirectoryListing($resources,"a",1,1,"all",1);

 $i = 0; //for illustrative purposes only 
 foreach ($dir as $item) {
     echo "<b><a href='resources/".$dir[$i]."'>".$dir[$i]."</a></b><br>";
     $i++;
 }

上記のコードは次のようなものを出力します:

FOLDER1
FOLDER1 / FILE1.PDF
FOLDER1 / FILE2.PDF
FOLDER2
FOLDER2 / FILE1.PDF
FOLDER2 / FILE2.PDF

以下のコメントに対する私の回答は次のとおりです。@hek2mglこれはまさに私がやろうとしていることです。ツリータイプのビューが欲しいのですが。

@popnoodlesを「ulli」形式に変換できれば、それは私が使用できると信じているものです。問題は、私は初心者のPHPerです...だからここで実用的な解決策を探しています。

@BjørneMalmanger含まれているクラスの内容は次のとおりです。

function getDirectoryListing($dirname, $sortorder = "a", $show_subdirs = 1,         $show_subdirfiles = 0, $exts = "all", $ext_save = 1) {
// This function will return an array with filenames based on the criteria you can set in the variables
// @sortorder : a for ascending (the standard) or d for descending (you can use the "r" for reverse as well, works the same)
// @show_subdirs : 0 for NO, 1 for YES - meaning it will show the names of subdirectories if there are any
// Logically subdirnames will not be checked for the required extentions
// @show_subdirfiles : 0 for NO, 1 for YES - meaning it will show files from the subdirs
// Files from subdirs will be prefixed with the subdir name and checked for the required extentions.
// @exts can be either a string or an array, if not passed to the function, then the default will be a check for common image files
// If exts is set to "all" then all extentions are allowed
// @ext_save : 1 for YES, 0 for NO - meaning it will filter out system files or not (such as .htaccess)

if (!$exts || empty($exts) || $exts == "") {
   $exts = array("jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif");
}
if ($handle = opendir($dirname)) {
   $filelist = array();
   while (false !== ($file = readdir($handle))) {

       // Filter out higher directory references
       if ($file != "." && $file != "..") {
           // Only look at directories or files, filter out symbolic links
           if ( filetype ($dirname."/".$file) != "link") {
               // If it's a file, check against valid extentions and add to the list
               if ( filetype ($dirname."/".$file) == "file" ) {
                   if (checkFileExtention($file, $exts, $ext_save)) {
                                   $filelist[] = $file;
                   }
               }
               // If it's a directory and either subdirs should be listed or files from subdirs add relevant names to the list
               else if ( filetype ($dirname."/".$file) == "dir" && ($show_subdirs == 1 || $show_subdirfiles == 1)) {
                   if ($show_subdirs == 1) {
                       $filelist[] = $file;
                   }
                   if ($show_subdirfiles == 1) {
                       $subdirname = $file;
                       $subdirfilelist = getDirectoryListing($dirname."/".$subdirname."/", $sortorder, $show_subdirs, $show_subdirfiles, $exts, $ext_save);
                       for ($i = 0 ; $i < count($subdirfilelist) ; $i++) {
                           $subdirfilelist[$i] = $subdirname."/".$subdirfilelist[$i];
                       }
                       $filelist = array_merge($filelist, $subdirfilelist);
                   }

               }

           }
       }
   }
   closedir($handle);

   // Sort the results
   if (count($filelist) > 1) {
       natcasesort($filelist);
       if ($sortorder == "d" || $sortorder == "r" ) {
           $filelist = array_reverse($filelist, TRUE);
       }
   }
   return $filelist;
  }
  else {
    return false;
 }
 }

 function checkFileExtention($filename, $exts, $ext_save = 1) {
 $passed = FALSE;
 if ($ext_save == 1) {
   if (preg_match("/^\./", $filename)) {
       return $passed;
   }
 }
 if ($exts == "all") {
               $passed = TRUE;
   return $passed;
 }
 if (is_string($exts)) {
   if (eregi("\.". $exts ."$", $filename)) {
                   $passed = TRUE;
       return $passed;
   }
  } else if (is_array($exts)) {
   foreach ($exts as $theExt) {
       if (eregi("\.". $theExt ."$", $filename)) {
           $passed = TRUE;
           return $passed;
        }
    }
  }
  return $passed;
  }
4

1 に答える 1

2

jstreeを見てください。これがあなたの望むものだと思います。(私はjstreeを使用してそれを行いました)。Jstreeはjavascriptライブラリであり、HTMLリスト(<ul>, <ol>)やjson、xmlなどのツリー構造を「+」を使用して制御可能なツリーとしてレンダリングし、必要に応じてフォルダを開閉できます。

もちろん、jstreeは単なるjavascriptの部分です。の出力をgetDirectoryListing()jstreeがサポートする形式の1つにフォーマットする必要があります。これは現在です

  • Json
  • XMl
  • HTML

ここに基本的な例があります。finiehdの場合、次のようになります。

ブラウザでの完成例

ツリーの開いているノードと閉じているノードをいじることができます。

ディレクトリリスト関数をjstreeのJSONを生成する関数に変更しました。実際には、このSO投稿から派生して、物事をすばやく機能させることができます。ありがとう!:)これがphpです。Webサーバーのフォルダーに配置し、名前を付けますtree.php

<?php

header('Content-Type: application/json');
echo json_encode(dir_to_jstree_array(__DIR__));

function dir_to_jstree_array($dir, $order = "a", $ext = array()) {

    if(empty($ext)) {
        $ext = array (
            "jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif"
        );
    }

    $listDir = array(
        'data' => basename($dir),
        'attr' => array (
            'rel' => 'folder'
        ),
        'metadata' => array (
            'id' => $dir
        ),
        'children' => array()
    );

    $files = array();
    $dirs = array();

    if($handler = opendir($dir))
    {
        while (($sub = readdir($handler)) !== FALSE)
        {
            if ($sub != "." && $sub != "..")
            {
                if(is_file($dir."/".$sub))
                {
                    $extension = pathinfo($dir."/".$sub, PATHINFO_EXTENSION);
                    if(in_array($extension, $ext)) {
                        $files []= $sub;
                    }
                }elseif(is_dir($dir."/".$sub))
                {
                    $dirs []= $dir."/".$sub;
                }
            }
        }

        if($order === "a") {
            asort($dirs);
        } else {
            arsort($dirs);
        }

        foreach($dirs as $d) {
            $listDir['children'][]= dir_to_jstree_array($d);
        }

        if($order === "a") {
            asort($files);
        } else {
            arsort($files);
        }

        foreach($files as $file) {
            $listDir['children'][]= $file;
        }

        closedir($handler);
    }
    return $listDir;
}

これが基本的なHTMLとjavascriptです。適切な名前を付けて、の横に配置しtree.phpます。jstreeのjson_dataプラグインをajaxと一緒に使用しています。また、typesプラグインを使用して、フォルダーとファイルのさまざまなタイプのアイコンをレンダリングしています。(必要に応じて、ファイルタイプごとにカスタムアイコンを設定することもできます)。htmlファイルの横に適切なfolder.pngとimage.pngを配置する必要があります。

<html>
  <head>
    <script type="text/javascript" src="jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="jstree-v.pre1.0/jquery.jstree.js"></script>
    <script type="text/javascript">

        $(function() {
          $('#dirtree').jstree({
            plugins : ["json_data", "themes", "types"],

            json_data : {
              ajax : {
                'url' : 'tree.php'
              }
            },

            'types': {
              'types' : {

                'folder' : {
                  'icon' : {
                    'image' : 'folder.png'
                  }
                },

                'default' : {
                  'icon' : {
                    'image' : 'image.png'
                  },
                }
              }
            }
          });
        }); 

    </script>
 </head>
 <body>
   <div id="dirtree"></div>
 </body>
</html>

それでおしまい!:) jstreeには多くの構成オプション、スタイリングオプション、プラグインがあることに注意してください。もちろん、私の例を拡張します。

jstreeのインストールとドキュメントについては、上記のjstreeプロジェクトページへのリンクを参照してください。

于 2013-01-17T23:16:18.667 に答える