简体   繁体   中英

PHP Recursively delete empty directories with SPL iterators

I'm struggling with how to delete a tree of empty directories in PHP using SPL iterators. Consider the following directory structure in which all directories are empty:

/topdir

  level1 level2 

I've tried the following:

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(
    '/topdir', RecursiveIteratorIterator::CHILD_FIRST
));

foreach ($it as $file) {
    if ($file->isDir()) {
        rmdir((string)$file);
    }
}

But RecursiveIteratorIterator::CHILD_FIRST prevents the bottom level file from being part of the loop and I get the standard Directory not empty E_WARNING because level1 is not empty.

How do I recursively delete a tree of empty directories using SPL Iterators? Note: I know how to do this with glob , scandir , etc. Please do not offer these/similar functions as solutions.

I feel like I must be missing something very elementary here ...

It is the RecursiveIteratorIterator that does the actual visiting of the child-directories. The RecursiveDirectoryIterator only provides the handles for it.

Therefore, you need to set the CHILD_FIRST flag on the RecursiveIteratorIterator and not on the RecursiveDirectoryIterator :

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/topdir', FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
);

foreach ($it as $file) {
    if ($file->isDir()) {
        rmdir((string)$file);
    }
}

To prevent warnings also add the ::SKIP_DOTS flag to RecursiveDirectoryIterator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM