Home > Article > Backend Development > Tree structure lists PHP classes of all files in the specified directory_PHP tutorial
//List all the files in the specified directory in a tree structure. If you want to know what subdirectories and files there are in a certain directory, you can call this class to view it, which is very convenient.
# Demonstration example:
$t = new TreeClimber( "asp" ); // Create a new object and set the directory to be listed: here is the asp directory
echo arrayValuesToString( $t ->getFileList( $t->getPath() ), "
n" );
function arrayValuesToString( $ar, $nl="", $dolast=true ) {// Call function
$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;
}
?>
//The following are Class file
class TreeClimber {
var $path;
var $fileList = array();
function TreeClimber( $path = "." ) {
$this->path = $path;
}
# Access path
function getPath() { return $this->path; }
function setPath( $v ) { $this->path = $v; }
// Returns the file list in the specified directory. If no directory is specified, the current directory will be used
// If the directory cannot be opened (perhaps without permission or the directory does not exist, it will be returned Is empty
//Proceed recursively
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( " Note: TreeClimber.getFileList( $dirname ): Cannot open $dirname!" );
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;
}
} //End of this type
?>