为PHP遍历目录和文件列表写了一个简单的类,并附上使用实例,大家参考使用吧
class getDirFile{
//返回数组@H_403_5@ private $DirArray = array();@H_403_5@ private $FileArray = array();@H_403_5@ private $DirFileArray = array();
private $Handle,$Dir,$File;
//获取目录列表@H_403_5@ public function getDir( & $Dir ){@H_403_5@ if( is_dir($Dir) ){@H_403_5@ if( false != ($Handle = opendir($Dir)) ){@H_403_5@ while( false != ($File = readdir($Handle)) ){@H_403_5@ if( $File!='.' && $File!='..' && !strpos($File,'.') ){@H_403_5@ $DirArray[] = $File;@H_403_5@ }@H_403_5@ }@H_403_5@ closedir( $Handle );@H_403_5@ }@H_403_5@ }else{@H_403_5@ $DirArray[] = '[Path]:\''.$Dir.'\' is not a dir or not found!';@H_403_5@ }@H_403_5@ return $DirArray;@H_403_5@ }
//获取文件列表@H_403_5@ public function getFile( & $Dir ){@H_403_5@ if( is_dir($Dir) ){@H_403_5@ if( false != ($Handle = opendir($Dir)) ) {@H_403_5@ while( false != ($File = readdir($Handle)) ){@H_403_5@ if( $File!='.' && $File!='..' && strpos($File,'.') ){@H_403_5@ $FileArray[] = $File;@H_403_5@ }@H_403_5@ }@H_403_5@ closedir( $Handle );@H_403_5@ }@H_403_5@ }else{@H_403_5@ $FileArray[] = '[Path]:\''.$Dir.'\' is not a dir or not found!';@H_403_5@ }@H_403_5@ return $FileArray;@H_403_5@ }
//获取目录/文件列表@H_403_5@ public function getDirFile( & $Dir ){@H_403_5@ if( is_dir($Dir) ){@H_403_5@ $DirFileArray['DirList'] = $this->getDir( $Dir );@H_403_5@ if( $DirFileArray ){@H_403_5@ foreach( $DirFileArray['DirList'] as $Handle ){@H_403_5@ $File = $Dir.DS.$Handle;@H_403_5@ $DirFileArray['FileList'][$Handle] = $this->getFile( $File );@H_403_5@ }@H_403_5@ }@H_403_5@ }else{@H_403_5@ $DirFileArray[] = '[Path]:\''.$Dir.'\' is not a dir or not found!';@H_403_5@ }@H_403_5@ return $DirFileArray;@H_403_5@ }
实例:(相对路径或绝对路径)
$getDirFile = new getDirFile();@H_403_5@$getFile_one = $getDirFile->getFile( $File_one_dir );@H_403_5@$getFile_two = $getDirFile->getFile( $File_two_dir );
print_r($getFile_one);@H_403_5@print_r($getFile_two);@H_403_5@?>@H_403_5@
$getDirFile = new getDirFile();@H_403_5@$getFile_one = $getDirFile->getFile( $File_one_dir );@H_403_5@$getFile_two = $getDirFile->getFile( $File_two_dir );
print_r($getFile_one);@H_403_5@print_r($getFile_two);@H_403_5@?>@H_403_5@
Array@H_403_5@(@H_403_5@ [0] => example.PHP@H_403_5@)@H_403_5@
$getDirFile = new getDirFile();@H_403_5@$getDirFile = $getDirFile->getDirFile( $Dir_dir );
[FileList] => Array@H_403_5@ (@H_403_5@ [example_one] => Array@H_403_5@ (@H_403_5@ [0] => example.sql@H_403_5@ [1] => example.txt@H_403_5@ )
[example_two] => Array@H_403_5@ (@H_403_5@ [0] => example.PHP@H_403_5@ )@H_403_5@ )@H_403_5@)@H_403_5@