`

php中的DirectoryIterator和RecursiveDirectoryIterator

    博客分类:
  • PHP
php 
阅读更多
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) )
        {
            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";
    }
?>
分享到:
评论

相关推荐

    PHP使用DirectoryIterator显示下拉文件列表的方法

    PHP中使用DirectoryIterator显示下拉文件列表,要遍历一个目录中的所有文件,我们可以使用DirectoryIterator,下面的例子演示了如何在页面中输出一个指定目录的文件列表 &lt;?php echo &lt;select name='file'&gt;\...

    php中通过DirectoryIterator删除整个目录的方法

    主要介绍了php中通过DirectoryIterator删除整个目录的方法,实例分析了php通过DirectoryIterator类操作目录的技巧,具有一定参考借鉴价值,需要的朋友可以参考下

    php计算指定目录下文件占用空间的方法

    php中可以通过 RecursiveDirectoryIterator 扩展 DirectoryIterator的getChildren() 方法提供访问子目录中的每一个元素的方法,下面的代码通过遍历访问目录下的所有文件,获取他们暂用的空间。 &lt;?php $dir = new...

    ssh:PHP 中的简单 SSH 客户端

    PHP 中的简单 SSH 客户端具有简单用户和密码身份验证的 SSH 连接 &lt;?phpuse Neto\net\ssh\SSHConnection;use Neto\net\ssh\auth\SSHPasswordAuthentication;$ssh = new SSHConnection();$ssh-&gt;open('127.0.0.1');$...

    php去掉文件前几行的方法

    比如去掉lrc文件中开头几行: [ti:] [ar:] [al:] [by:cww.99Lrc.net] [00:00.59]dasfdasfasdf [00:30.18]dafadsf php实现代码如下: &lt;?php foreach (new DirectoryIterator('./') as $fileInfo) { if($fileInfo...

    PHP-CSS-Sprites-Generator:简单的 CSS 精灵生成器 PHP 类。 从图片文件夹生成精灵

    此脚本循环遍历文件夹中的所有图片并将其放置在适合的位置。依赖关系api使用示例 $ spriteGrid = new yl\gfx\ SpriteGrid ();$ spriteGrid -&gt; importImagesFromFolder ( new DirectoryIterator ( 'images' ));$ ...

    去免费广告方法

    方法一:CSS隐藏,安全性90%,可能会被K! ... &lt;style&gt;#conash3D0 {display:none} 方法二:中文屏蔽,godaddy网管应该没有用中文,安全性 95%... Pear DB 新手入门指南2008-05-21 13:27:04 使用SPL DirectoryIterator对象

Global site tag (gtag.js) - Google Analytics