PHP递归目录路径 [英] PHP recursive directory path

查看:140
本文介绍了PHP递归目录路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能返回完整目录树

function getDirectory( $path = '.', $level = 0 ){

$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.

$dh = @opendir( $path );
// Open the directory to the handle $dh

while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory

    if( !in_array( $file, $ignore ) ){
    // Check that this file is not to be ignored

        $spaces = str_repeat( ' ', ( $level * 4 ) );
        // Just to add spacing to the list, to better
        // show the directory tree.

        if( is_dir( "$path/$file" ) ){
        // Its a directory, so we need to keep reading down...

            echo "<strong>$spaces $file</strong><br />";
            getDirectory( "$path/$file", ($level+1) );
            // Re-call this same function but on a new directory.
            // this is what makes function recursive.

        } else {

            echo "$spaces $file<br />";
            // Just print out the filename

        }

    }

}

closedir( $dh );
// Close the directory handle

}

但我想做的是搜索文件/文件夹并返回它的路径,我该怎么办?你有这样的功能,还是给我一些如何做的提示?

but what i want to do is to search for a file/folder and return it's path, how can i do that? do you have such a function or can you give me some tips on how to do this?

推荐答案

尝试使用 RecursiveIteratorIterator RecursiveDirectoryIterator

$path = realpath('/path/you/want/to/search/in');

$objects = new RecursiveIteratorIterator(
               new RecursiveDirectoryIterator($path), 
               RecursiveIteratorIterator::SELF_FIRST);

foreach($objects as $name => $object){
    if($object->getFilename() === 'work.txt') {
        echo $object->getPathname();
    }
}

附加阅读:

  • http://www.phpro.org/tutorials/Introduction-to-SPL.html

这篇关于PHP递归目录路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆