需要帮助格式化PHP中的目录列表的结果,javascript树控件 [英] Need help formatting results of a directory listing in PHP, javascript tree control

查看:93
本文介绍了需要帮助格式化PHP中的目录列表的结果,javascript树控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP列出一个特定文件夹中的所有文件夹和文件。使用下面的代码,我设法列出一个长列表中的所有文件和文件夹。现在我真正要做的就是列出它们,以便我可以使用HTML / jquery将目录结果显示为文件夹旁边带有+标记,这样它们就可以扩展,但我无法弄清楚如何格式化结果PHP就是为了做到这一点。

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

$ i = 0; //仅用于说明目的
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如果我能把它变成ul li格式,我认为我可以使用它。问题是,我是初学PHPer ...所以在这里寻找一个有效的解决方案。



@BjørneMalmanger这是包含类的内容:

 函数getDirectoryListing($ dirname,$ sortorder =a,$ show_subdirs = 1,$ show_subdirfiles = 0, $ exts =all,$ ext_save = 1){
//此函数将返回一个数组,文件名基于您可以在变量中设置的条件
// @sortorder:a for ascending(降序的标准)或d(你也可以使用r反转,同样的工作)
// @show_subdirs:0代表NO,1代表YES - 意味着它将显示子目录的名称有任何
//不会检查逻辑子目录的所需扩展名
// @show_subdirfiles:0代表NO,1代表YES - 意味着它将显示子目录中的文件
//子目录中的文件将以子目录名为前缀,并检查所需的扩展名。
// @exts可以是字符串也可以是数组,如果没有传递给函数,则默认将检查常见的图像文件
//如果exts设置为all则所有扩展都允许
// @ext_save:1表示YES,0表示NO - 意味着它将过滤掉系统文件(例如.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))){

//过滤掉更高的目录引用
if($ file!=。 && $ file!=..){
//只查看目录或文件,过滤掉符号链接
if(filetype($ dirname。/。$ file)! =link){
//如果是文件,请检查有效的扩展名并添加到列表
if(filetype($ dirname。/。$ file)==file) {
if(checkFileExtention($ file,$ exts,$ ext_save)){
$ filelist [] = $ file;
}
}
//如果它是一个目录,应该列出子目录或子目录中的文件将相关名称添加到列表
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);

//对结果排序
if(count($ filelist)> 1){
natcasesort($ filelist);
if($ sortorder ==d|| $ sortorder ==r){
$ filelist = array_reverse($ filelist,TRUE);
}
}
返回$ filelist;
}
else {
返回false;
}
}

函数checkFileExtention($ filename,$ exts,$ ext_save = 1){
$ pass = FALSE;
if($ ext_save == 1){
if(preg_match(/ ^ \。/,$ filename)){
return $ passing;
}
}
if($ exts ==all){
$ pass = TRUE;
返回$通过;
}
if(is_string($ exts)){
if(eregi(\。。$ exts。$,$ filename)){
$传递= TRUE;
返回$通过;
}
}否则if(is_array($ exts)){
foreach($ exts as $ theExt){
if(eregi(\。。$ theExt。 $,$ filename)){
$ pass = TRUE;
返回$通过;
}
}
}
返回$ pass;
}


解决方案

看看,以便快速工作。谢谢! :)这是php。将其放在网络服务器的一个文件夹中,并将其命名为 tree.php

 <?php 

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

函数dir_to_jstree_array($ dir,$ order =a,$ ext = array()){

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

$ listDir =数组(
'data'=> basename($ dir),
'attr'=>数组(
'rel'=>'文件夹'
),
'元数据'=>数组(
'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);
}其他{
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);
}
返回$ listDir;
}

这是基本的HTML和javascript。给它一个正确的名称并将其放在 tree.php 旁边。我正在使用jstree的json_data插件和ajax。此外,我正在使用类型插件为文件夹和文件呈现不同类型的图标。 (如果需要,也可以为每种文件类型设置一个自定义图标)。您必须在html文件旁边放置一个正确的folder.png和image.png。

 < html> 
< head>
< script type =text / javascriptsrc =jquery-1.8.3.min.js>< / script>
< script type =text / javascriptsrc =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'
}
},

'类型':{
'类型':{

'文件夹':{
'图标':{
'image':'folder.png'
}
},

'默认':{
'图标':{
'image':'image.png'
},
}
}
}
});
});

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

多数民众赞成! :)请注意,您有许多配置选项,样式选项和jstree插件。你当然会扩展我的例子。



请参阅上面的链接到jstree项目页面,了解有关安装jstree和文档的信息。


I am trying to list all of the folders and files inside one particular folder using PHP. Using the code below I have managed to list all of the files and folders in one long list. Now what i am really trying to do is to list them such that i can use HTML/jquery to show the directory results as folders with + marks next to them so they can be expanded, but I cannot figure out how to format the results in PHP in order to do that.

 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++;
 }

The code above will output something like this:

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

Here are my responses to the comments below: @hek2mgl that is exactly what I am trying to do. I would like a tree type view.

@popnoodles if I can get it into a "ul li" format, that is something I believe I can work with. The thing is, I am a beginner PHPer... so looking for a working solution here.

@Bjørne Malmanger Here is the contents of the included class:

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;
  }

解决方案

Have a look at jstree. I think this is what you want. (I'm done it using jstree). Jstree is a javascript library that can be used control to render tree structures like HTML lists (<ul>, <ol>) or json or xml as controllable tree with '+' to open and close a folder like you wished.

Of course jstree is just the javascript part. You'll have to format the outputs of your getDirectoryListing() to one of the formats jstree supports. This are currently

  • Json
  • XMl
  • Html

Here comes a basic example. When finiehd it will look like this:

You can play around with the tree open and close nodes.

I've changed your directory listing function to a one that produces JSON for jstree. Its actually derived from this SO post to get things quick working. Thanks! :) Here is the php. Place it in a folder in your webserver and name it 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;
}

Here comes the basic HTML and javascript. Give it a proper name and place it beside the tree.php. I'm using the json_data plugin of jstree together with ajax. Also I'm using the types plugin to render different types of icons for folders and files. (It would be possible to have a custom icon for each filetype too, if you want). You'll have to place a proper folder.png and image.png beside the html file.

<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>

Thats it! :) Note that you have many configuration options, styling options and plugins to jstree. You'll of course extend my example.

Please refer to the link above to the jstree project page for information about installation of jstree and the documentation.

这篇关于需要帮助格式化PHP中的目录列表的结果,javascript树控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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