搜尋
首頁後端開發php教程 php中的DirectoryIterator跟RecursiveDirectoryIterator

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
優化PHP代碼:減少內存使用和執行時間優化PHP代碼:減少內存使用和執行時間May 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP電子郵件:分步發送指南PHP電子郵件:分步發送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

如何通過PHP發送電子郵件:示例和代碼如何通過PHP發送電子郵件:示例和代碼May 09, 2025 am 12:13 AM

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

高級PHP電子郵件:自定義標題和功能高級PHP電子郵件:自定義標題和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP發送電子郵件的指南使用PHP和SMTP發送電子郵件的指南May 09, 2025 am 12:06 AM

使用PHP和SMTP發送郵件可以通過PHPMailer庫實現。 1)安裝並配置PHPMailer,2)設置SMTP服務器細節,3)定義郵件內容,4)發送郵件並處理錯誤。使用此方法可以確保郵件的可靠性和安全性。

使用PHP發送電子郵件的最佳方法是什麼?使用PHP發送電子郵件的最佳方法是什麼?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依賴注入的最佳實踐PHP中依賴注入的最佳實踐May 08, 2025 am 12:21 AM

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

PHP性能調整技巧和技巧PHP性能調整技巧和技巧May 08, 2025 am 12:20 AM

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具