Home > Backend Development > PHP Tutorial > Tree structure lists the php code of all files in the directory

Tree structure lists the php code of all files in the directory

WBOY
Release: 2016-07-25 09:00:32
Original
841 people have browsed it
In this article, a simple PHP class is implemented to list all the files in the specified directory in a weighted structure. Friends who are interested can take a look.

List all the files in the specified directory in a tree structure. In this way, all the files in the directory will be clearly structured in front of you. You can know what files there are at a glance, which is very convenient.

Example,

<?
/**
 * 列出目录中所有文件
 * by 程序员之家 bbs.it-home.org
*/

#例子
$t = new TreeClimber( "asp" ); //新建物件,设置需要列出的目录:在此为asp目录
echo arrayValuesToString( $t->getFileList( $t->getPath() ), "<BR>\n" );

function arrayValuesToString( $ar, $nl="", $dolast=true ) {//调用函数
$str = "";
reset( $ar );
$size = sizeof( $ar );
$i = 1;
while( list( $k, $v ) = each( $ar ) ) {
if ( $dolast == false ) {
if ( $i < $size ) {
$str .= $ar[$k].$nl;
}
else {
$str .= $ar[$k];
}
}
else {
$str .= $ar[$k].$nl;
}
$i++;
}
return $str;
}

//类 TreeClimber
class TreeClimber {
var $path;
var $fileList = array();
function TreeClimber( $path = "." ) {
$this->path = $path;
}

# 存取路径
function getPath() { return $this->path; }
function setPath( $v ) { $this->path = $v; }

// 返回指定目录里的文件列表,如果没有指定目录,将使用当前目录
//如果不能打开目录(可能没权限或目录不存在,将返回为空
//以递归方式进行
function getFileList( $dirname=null, $returnDirs=false, $reset=true ) {
if ( $dirname == null ) { $dirname = $this->path; }
# else { $this->setPath( $dirname ); }
# dout( "Recursing into $dirname..." );
if ( $reset ) {
$this->fileList = array();
}
$dir = opendir( $dirname );
if ( ! $dir ) {
print( "<B><FONT COLOR=#FF0000>注意: TreeClimber.getFileList( $dirname ): 不能打开 $dirname!</FONT></B>" );
return null;
}
while( $file = readdir( $dir ) ) {
if ( ereg( "^\.$", $file ) || ereg( "^\.\.$", $file ) ) continue;
if ( is_dir( $dirname."/".$file ) ) {
$this->getFileList( $dirname."/".$file, $returnDirs, false );
if ( $returnDirs ) { $this->fileList[] = $dirname."/".$file;}
}
else { $this->fileList[] = $dirname."/".$file; }
}
sort( $this->fileList );
return $this->fileList;
}
}
?>
Copy after login
When you use the above PHP class, remember to test it in a directory with fewer files first to get a clear tree structure. Of course, you can also extend this class to achieve more powerful functions.


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template