日期:2014-05-17  浏览次数:20513 次

php中的DirectoryIterator和RecursiveDirectoryIterator
php中,可以用用DirectoryIterator获取指定目录的文件或者目录.
$path = "/tmp";  
$oDir = new DirectoryIterator($path);  
foreach($oDir as $file)  
{  
  if($file->isfile())  
  {  
    $tmpFile['link'] = $file->getPath();  
    $tmpFile['name'] = $file->getFileName();  
    $tmpFile['type'] = 'file';  
    $tmpFile['size'] = _cal_size($file->getSize());  
    $tmpFile['mtime'] = $file->getMTime();  
    $arrFile[] = $tmpFile;  
  }  
}  
print_r($arrFile);  
/* output 
Array 
( 
    [0] => Array 
        ( 
            [link] => /tmp 
            [name] => scim-panel-socket-:0-root 
            [type] => dir 
            [size] => 0b 
            [mtime] => 1222049895 
        ) 
 
    [1] => Array 
        ( 
            [link] => /tmp 
            [name] => .font-unix 
            [type] => dir 
            [size] => 4k 
            [mtime] => 1241417372 
        ) 
) 
*/  


RecursiveDirectoryIterator 获取目录下所有的文件,包括子目录 ,其中搭配:
RecursiveIteratorIterator使用.
(RecursiveIteratorIterator是个递归迭代器,其后可选带四个参数(只能任一)

RecursiveIteratorIterator::LEAVES_ONLY
默认,已在__construct中设定使用
作用是去枝留叶,跳过空节点,只递归取实值
举例就是
1.递归文件夹取文件时跳过文件夹本身,只取文件夹下面的文件,输出的项全部是file(文件和各级子文件夹的文件)
2.多维数组就跳过前几维的key,而取value,输出的每一项都不是array
3.XML只取值(text),不输出节点名,当然还要视乎你设定获取xml什么内容

RecursiveIteratorIterator::SELF_FIRST
各项都包含,例如递归文件夹就会连同子文件夹名称也作为其中项输出,顺序是先父后子

RecursiveIteratorIterator::CHILD_FIRST
同上,但顺序是先子后父,./test/test.php会在./test(文件夹)前面)

$path = "/tmp/"; 
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); 
foreach($objects as $object) 

  $tmpFile['link'] = $object->getPath(); 
  $tmpFile['name'] = $object->getFileName(); 
  $tmpFile['type'] = $object->isFile() ? 'file' : 'dir'; 
  $tmpFile['size'] = _cal_size($object->getSize()); 
  $tmpFile['mtime'] = $object->getMTime(); 
  $arrFile[] = $tmpFile; 

print_r($arrFile); 
/*
output:
Array
(
    [0] => Array
        (
            [link] => /tmp
            [name] => scim-panel-socket-:0-root
            [type] => dir
            [size] => 0b
            [mtime] => 1222049895
        )

    [1] => Array
        (
            [link] => /tmp/.font-unix
            [name] => fs7100
            [type] => dir
            [size] => 0b
            [mtime] => 1241417372
        )
)
*/ 

再来看个例子:
<?php

/*** the target directory, no trailling slash ***/
$directory = './';

try
    {
        /*** check if we have a valid directory ***/
        if( !is_dir($directory) )
        {