スポンサーリンク

PHPでファイル一覧を取得して開閉可能なツリー形式で表示する

PHPでファイル一覧を取得し、それをツリー形式で表示したかったので調べていた時に見つけたのがこちら。

jQueryを使ってディレクトリツリーを表示させるPHP、配布します! | ITキヲスク
http://smkn.xsrv.jp/blog/2009/04/directory_tree_with_php_and_jquery/

やりたかった事は殆ど実現出来ていましたが、自身の環境で使いやすいようにカスタマイズしました。

  • 関数を1つにまとめた
  • PHP内のクォーテーションの囲み方を変更
  • 都度echoしている部分を一旦配列に入れ、後で一気に出力するように変更
  • フォルダとファイルのアイコンを追加表示、その他CSS修正(簡素化)
  • HTMLの記述を最近っぽく、JS読み込み位置変更
<?php
/*////////////////////////////////////////
Base-create this script -> Lateral Code
  http://www.lateralcode.com/
Modification & redistribute -> ITキヲスク
  http://smkn.xsrv.jp/blog/
Modified by YUKI
  https://wynes.info/techblog/
////////////////////*/////////////////////
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ディレクトリツリー\(^o^)/</title>
<link rel="stylesheet" type="text/css" href="//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<style type="text/css">
#dir_tree ul {
  list-style-type: none;
  padding-left: 1em;
  margin-bottom:1em;
}
#dir_tree ul:first-child {
  padding-left: 0;
}
#dir_tree a, #dir_tree li {
  text-decoration: none;
}
</style>
</head>
<body>
<!-- Menu Start -->
<div id="dir_tree">
<?php
  $path = '/home/*****/www/';
  foreach(createDir($path) as $html){
    echo $html;
  }

  function createDir($path = '.')
  {
    if ($handle = opendir($path))
    {
      $html[] = '<ul>';
      $queue = array();
      while (false !== ($file = readdir($handle)))
      {
        if (is_dir($path.$file) && $file != '.' && $file !='..') {
          $html[] = '<li><span class="dir"><span class="ion-folder"> '.$file.'</span></span>';
          $html = array_merge($html, createDir($path.$file.'/'));
          $html[] = '</li>';
        } else if ($file != '.' && $file !='..') {
          $queue[] = $file;
        }
      }
      foreach ($queue as $file)
      {
        $html[] = '<li><a href='.$path.$file.'><span class="ion-document"> '.$file.'</span></a></li>';
      }
      $html[] = '</ul>';
      return $html;
    }
  }
?>
</div>
<!-- End Menu -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(function() {
  $("span.dir").css("cursor", "pointer").prepend("+ ").click(function() {
    $(this).next().toggle("fast");

    var v = $(this).html().substring( 0, 1 );
    if ( v == "+" )
      $(this).html( "-" + $(this).html().substring( 1 ) );
    else if ( v == "-" )
      $(this).html( "+" + $(this).html().substring( 1 ) );
  }).next().hide();

  $("#dir_tree a, #dir_tree span.dir").hover(function() {
      $(this).css("font-weight", "bold");
  }, function() {
      $(this).css("font-weight", "normal");
  });
});
</script>
</body>
</html>

しかし、本当はこれを作る前にJavascriptのツリー表示ライブラリを使ってリッチなものを作ろうとしていました。

Dynatree

JSONでツリー構造を定義するようなので、配列を作ってjsonencodeするつもりでしたが…子のディレクトリを持つ深い階層にも対応した配列の作り方(アルゴリズム)がどうしても分からず、結局断念。どなたか作って下さい(切実)

タイトルとURLをコピーしました