This time we will introduce a directory iterator in the SPL library. Its function is very simple, as the name suggests, is to get the contents of the specified directory. We used to have to go through a directory and get all of the files in that directory, so it was a bit of a hassle to write this code, so PHP has this built-in API that, when you type in a specific directory, returns all of the subdirectories and files in that directory. Of course, it’s not a tree, it’s not a tree, it’s not a tree, it’s a tree, it’s a tree.

Without further ado, let’s look at the code:

$path = $argv[1];

// Get all contents of the directory
$dirs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

foreach($dirs as $k= >$d) {echo 'key:'. $k, PHP_EOL;
    if($d->isDir()){
        echo $d->getPathname(), PHP_EOL;
    }else{
        echo $d->getFilename(), PHP_EOL; }}/ / execute PHP PHP to get all the content of the RecursiveDirectoryIterator. PHP.. /

// key:.. /.
/ /.. /.
// key:.. /..
/ /.. /..
// key:.. /source
/ /.. /source
// key:.. /source/.
/ /.. /source/.
// key:.. /source/..
/ /.. /source/..
// key:.. / source/PHP to get all the content of the RecursiveDirectoryIterator. PHP
/ / PHP to get all the content of the RecursiveDirectoryIterator. PHP
// key:.. /source/PHP
// PHP reads large files
// key:.. /PHP large file read operation. Md
// PHP reads large files. Md
// key:.. / PHP to get all the content of the RecursiveDirectoryIterator, md
/ / PHP to get all the content of the RecursiveDirectoryIterator, md

Copy the code

Just one line of code, and then just loop through the iterator. From the result, we can see that the source directory is first traversed and then the external file content is traversed. All contents in the directory are obtained according to the order of directory and file name. It’s a lot easier than writing our own recursive function.

What if we wanted to get all the PHP files in the directory and calculate their total file size? Using this set of iterators can also be done very simply by adding a regular iterator to filter the contents of the previous iterator:

// Get all PHP files
$regIts = new RegexIterator($dirs.'/^.+\.php$/i');
$fileSize = 0;
foreach($regIts as $k= >$p) {echo $p->getSize() . ' ' .  $k, PHP_EOL;
    $fileSize+ =$p->getSize();
}
echo 'Total '.$fileSize, PHP_EOL;

/ / 622.. / source/PHP to get all the content of the RecursiveDirectoryIterator. PHP
/ / 869.. /source/PHP
// Total 1491
Copy the code

Feel like LS – L, can be convenient for us to carry out directory related operations. So much for using this class. There are many more capabilities in the SPL library that we can explore, learn and practice slowly, and improve our ability to program gracefully.

Test code: github.com/zhangyue050…

Reference document: “PHP7 programming combat” www.php.net/manual/en/c… www.php.net/manual/en/c…