首页 >后端开发 >php教程 > php中的DirectoryIterator跟RecursiveDirectoryIterator

php中的DirectoryIterator跟RecursiveDirectoryIterator

WBOY
WBOY原创
2016-06-13 12:41:23959浏览

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
        )
)
*/ 

再来看个例子:

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

try
    {
        /*** check if we have a valid directory ***/
        if( !is_dir($directory) )
        {
            throw new Exception('Directory does not exist!'."\n");
        }

        /*** check if we have permission to rename the files ***/
        if( !is_writable( $directory ))
        {
            throw new Exception('You do not have renaming permissions!'."\n");
        }

   
        /**
        *
        * @collapse white space
        *
        * @param string $string
        *
        * @return string
        *
        */
        function collapseWhiteSpace($string)
        {
            return  preg_replace('/\s+/', ' ', $string);
        }

        /**
        * @convert file names to nice names
        *
        * @param string $filename
        *
        * @return string
        *
        */
        function safe_names($filename)
        {
            $filename = collapseWhiteSpace($filename);
            $filename = str_replace(' ', '-', $filename);
            $filename = preg_replace('/[^a-z0-9-.]/i','',$filename);
            return  strtolower($filename);
        }

        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, 0));
        /*** loop directly over the object ***/
        while($it->valid())
            {
            /*** check if value is a directory ***/
            if(!$it->isDot())
            {
                if(!is_writable($directory.'/'.$it->getSubPathName()))
                {
                    echo 'Permission Denied: '.$directory.'/'.$it->getSubPathName()."\n";
                }
                else
                {
                    /*** the old file name ***/
                    $old_file = $directory.'/'.$it->getSubPathName();

                    /*** the new file name ***/
                    $new_file = $directory.'/'.$it->getSubPath().'/'.safe_names($it->current());
                   
                    /*** rename the file ***/
                    rename ($old_file, $new_file);

                    /*** a little message to say file is converted ***/
                    echo 'Renamed '. $directory.'/'.$it->getSubPathName() ."\n";
                }
            }
            /*** move to the next iteration ***/
            $it->next();
        }
       
        /*** when we are all done let the user know ***/
        echo 'Renaming of files complete'."\n";
    }
    catch(Exception $e)
    {
        echo $e->getMessage()."\n";
    }
?>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn