PHP读取目录树,文件名的一个类:Directory Reader Object

在国内论坛上找了很久也没有找到,一般都是读取一个目录下的文件列表,后来到国外的一个网站找到了这个类,写得不错,备忘·
可以读取目录下的目录,文件等。

[php]
<?php
 main();

 function main(){
 //Set Variables
 $testDirName = "../php/";
 $fileListArray = array();
 $dirListArray = array();

$aDirectory = new DirReader($testDirName);

// Store File List in Array
$fileListArray = $aDirectory->getFileList();
$dirListArray = $aDirectory->getDirList();

echo "\n";
echo "</pre><pre>\n";

echo "Reading Directory: ".  $aDirectory->getDirPath() ."\n";
echo "Current Directory: ". getcwd() ."\n";

echo "-- Files in Directory --\n";
foreach ($fileListArray as $filename) {
    echo "File: $filename\n";
}

echo "\n-- Sub Directories --\n";
foreach ($dirListArray as $filename){
    echo "Sub dir: $filename\n";
}
echo "</pre>
\n";
}

class DirReader{
private $dh; # Directory Handle
private $basedir; # Base Directory passed to the object
private $fileNameArray=array();
private $dirNameArray=array();

function __construct($dirname){
$this->basedir = $dirname;
$this->dh = dir($dirname) or die($php_errormsg);
$this->parseDirectory();
}

function parseDirectory(){
$filename = "";
while (false !== ($filename = $this->dh->read())){
$fullpath = $this->basedir . '/' . $filename;
if (is_file($fullpath)){
array_push($this->fileNameArray, $filename);
}else{
array_push($this->dirNameArray, $filename);
}
}
}

// Get all the files in the directory
function getFileList(){
return $this->fileNameArray;
}

// Get all the sub directories in the directory
function getDirList(){
return $this->dirNameArray;
}

function getDirPath(){
return $this->dh->path;
}
}
?>
[/php]



The class is defined on lines 35-57. Lines 36-39 define the object properties. The private keyword is new to PHP5. Lines 41-44 initialize variables get the directory passed to it when the object is created. The constructor then calls the parseDirectory function which reads the directory contents into separate file and directory arrays. The code that reads the info, line 49, comes almost directory out of the documentation. This example uses the object oriented approach to reading a directory handle. Line 51 checks if this is a file or directory. Then, the file name gets pushed into the appropriate place. The methods on lines 60 to 72 allow you to retrieve your desired information.


点此下载此文件: dirreader