エントリー

PHPでディレクトリの内容をリスト表示

自分用にメモ。

ディレクトリの内容をリストですべて表示するプログラム。記事のツリー表示や全文検索やサイトマップ自動作成などに応用できるかもしれません。

<?php

function get_tree($path)
{ 
  if (!is_dir($path)) {
    return;
  }

  $trees = array();

  if ($dir = scandir($path)) {
    foreach ($dir as $entry) {
      if ($entry == '.' or $entry == '..') {
        continue;
      }
      if (is_dir($path . '/' . $entry)) {
        $trees[$entry] = get_tree($path . '/' . $entry);
      } else {
        $trees[$entry] = $path . '/' . $entry;
      }
    }
  }

  return $trees;
}

function put_tree($trees)
{
  if (!is_array($trees)) {
    return;
  }

  echo '<ul>';

  foreach ($trees as $key => $value) {
    if (is_array($value)) { 
      echo '<li>[d] ' . $key;
      put_tree($value);
      echo '</li>';
    } else {
      echo '<li>[f] '.  $key . '</li>';
    }
  }

  echo '</ul>';

  return;
}

$dir   = './sample'; //sampleディレクトリの内容を表示
$trees = get_tree($dir);

?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=Shift_JIS">
<title>ディレクトリ表示</title>
</head>
<body>
<?php put_tree($trees); ?>
</body>
</html>

実行すると以下のようにリストタグでツリー表示されます。ディレクトリには [d]、ファイルには [f] が表示されます。

<ul>
  <li>[d] sample1
    <ul>
      <li>[d] sample1-1
        <ul>
          <li>[f] sample1-1-1.txt</li>
          <li>[f] sample1-1-2.txt</li>
        </ul>
      </li>
      <li>[f] sample1-1.txt</li>
      <li>[f] sample1-2.txt</li>
    </ul>
  </li>
  <li>[d] sample2
    <ul>
      <li>[f] sample2-1.txt</li>
      <li>[f] sample2-2.txt</li>
    </ul>
  </li>
  <li>[f] test1.txt</li>
  <li>[f] test2.txt</li>
</ul>

ページ移動

コメント

  • コメントはまだありません。

コメント登録

  • コメントを入力してください。
登録フォーム
名前
メールアドレス
URL
コメント
閲覧制限
投稿キー(スパム対策に、投稿キー を半角で入力してください。)

ユーティリティ

2010年03月

- 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 - - -

検索

エントリー検索フォーム
キーワード

Feed

RSSリーダー

  • JavaScriptをONにすると、RSSリーダーが表示されます。

利用ツール