您的位置:首页 > 编程语言 > PHP开发

PHP遍历目录和文件列表

2012-02-07 11:00 197 查看
对于PHP遍历目录和文件列表,下面写了一个简单的类,并附上使用实例,如有所疏漏及错误,请大家指点!
<?php
define('DS', DIRECTORY_SEPARATOR);

class getDirFile{

//返回数组
private $DirArray  = array();
private $FileArray = array();
private $DirFileArray = array();

private $Handle,$Dir,$File;

//获取目录列表
public function getDir( & $Dir ){
if( is_dir($Dir) ){
if( false != ($Handle = opendir($Dir)) ){
while( false != ($File = readdir($Handle)) ){
if( $File!='.' && $File!='..' && !strpos($File,'.') ){
$DirArray[] = $File;
}
}
closedir( $Handle );
}
}else{
$DirArray[] = '[Path]:\''.$Dir.'\' is not a dir or not found!';
}
return $DirArray;
}

//获取文件列表
public function getFile( & $Dir ){
if( is_dir($Dir) ){
if( false != ($Handle = opendir($Dir)) ) {
while( false != ($File = readdir($Handle)) ){
if( $File!='.' && $File!='..' && strpos($File,'.') ){
$FileArray[] = $File;
}
}
closedir( $Handle );
}
}else{
$FileArray[] = '[Path]:\''.$Dir.'\' is not a dir or not found!';
}
return $FileArray;
}

//获取目录/文件列表
public function getDirFile( & $Dir ){
if( is_dir($Dir) ){
$DirFileArray['DirList'] = $this->getDir( $Dir );
if( $DirFileArray ){
foreach( $DirFileArray['DirList'] as $Handle ){
$File = $Dir.DS.$Handle;
$DirFileArray['FileList'][$Handle] = $this->getFile( $File );
}
}
}else{
$DirFileArray[] = '[Path]:\''.$Dir.'\' is not a dir or not found!';
}
return $DirFileArray;
}

}
?>


实例:(相对路径或绝对路径)

1.获取目录列表

<?php
$Dir_dir  = './example';

$getDirFile = new getDirFile();
$getDir = $getDirFile->getDir( $Dir_dir );

print_r($getDir);
?>
显示:

Array
(
[0] => example_one
[1] => example_two
)


2.获取文件列表

<?php
$File_one_dir = './example/example_one';
$File_two_dir = 'E:/Workspace/mycode/getDirFile/example/example_two';

$getDirFile = new getDirFile();
$getFile_one = $getDirFile->getFile( $File_one_dir );
$getFile_two = $getDirFile->getFile( $File_two_dir );

print_r($getFile_one);
print_r($getFile_two);
?>
显示:
Array
(
[0] => example.sql
[1] => example.txt
)

Array
(
[0] => example.php
)


3.获取目录/文件列表

<?php
$Dir_dir  = './example';

$getDirFile = new getDirFile();
$getDirFile  = $getDirFile->getDirFile( $Dir_dir );

print_r($getDirFile);
?>
显示:

Array
(
[DirList] => Array ( [0] => example_one [1] => example_two )

[FileList] => Array
(
[example_one] => Array
(
[0] => example.sql
[1] => example.txt
)

[example_two] => Array
(
[0] => example.php
)

)

)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: