原文地址:http://blog.makemepulse.com/2008/02/18/tips-easy-way-to-find-a-file-in-subdirectory-with-php/
- <?php
- class DirectorySearch {
- private
- $iterator,
- $directoryname;
- public function __construct($directoryname){
- $this->iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directoryname,RecursiveDirectoryIterator::KEY_AS_FILENAME));
- }
- public function find($filename){
- foreach($this->iterator as $entry){
- if($filename == $this->iterator->current()){
- return $this->iterator->getPathName();
- }
- }
- return false;
- }
- }
实际应用:
- <?php
- $directory = dirname(__FILE__)."/directory";
- $search_directory = new DirectorySearch($directory);
- $path_file = $search_directory->find("file_to_find.php");
- if($path_file !== false){
- //include_once($path_file);
- echo $path_file;
- }
If we don’t use the KEY_AS_FILENAME with the recursiveDirectoryIterator we will have the whole path of the file in $this->iterator->current();
如果我们不使用recursiveDirectoryIterator类的KEY_AS_FILENAME,我们也可以使用文件的全路径$this->iterator->current();
All of this is a basic example of the RecursiveIteratorIterator with the RecursiveDirectoryIterator. SPL is a very powerfull toolkit !
这只是RecursiveDirectoryIterator的一个基本的功能,不得不说,SPL是一个非常好的工具。
自己的话:
以前遍历目录找文件一般是两种方法:1、opendir,2、glob,然后来遍历整个目录。如今SPL里有现成的,那肯定是这样的速度更快,效率更高喽?只是。。。不知道对中文文件名的支持会怎么[已测试,让我失望]
- <?php
- function read_dir( $dir) {
- $array = array();
- $d = dir($dir);
- while (false !== ($entry = $d->read())) {
- if($entry!='.' && $entry!='..') {
- $entry = $dir.'/'.$entry;
- if(is_dir($entry)) {
- $array[] = $entry;
- $array = array_merge($array, read_dir($entry));
- } else {
- $array[] = $entry;
- }
- }
- }
- $d->close();
- return $array;
- }
- function get_file ($file, $file_path ){
- foreach ( $file_path as $_k => $_v ){
- if ( basename($_v) == $file ){
- return $_v ;
- }
- }
- }
- ?>
测试下来。。。让我失望。
- <?php
- $directory = dirname(__FILE__)."/Discuz!_6.0.0_SC_UTF8";
- $sTime = microtime(true);
- $search_directory = new DirectorySearch($directory);
- $path_file = $search_directory->find("buy中文.htm");
- if($path_file !== false){
- //include_once($path_file);
- echo( $path_file );
- }
- echo '<pre>';
- print_r( microtime(true) - $sTime );
- echo '</pre>';
- $sTime = microtime(true);
- $f = 'buy中文.htm';
- echo( get_file($f,read_dir($directory)) );
- echo '<pre>';
- print_r( microtime(true) - $sTime );
- echo '</pre>';
使用CLass的时间是0.86550688743591
使用function的时间是:0.54081797599792
鉴定完毕:支持中文文件名