How to Recursively Read Subdirectories and Process Files in PHP?

Mary-Kate Olsen
Release: 2024-10-23 06:33:29
Original
598 people have browsed it

How to Recursively Read Subdirectories and Process Files in PHP?

How to Read Sub-directories and Iterate Over Files in PHP

To iterate over files in subdirectories, you can leverage PHP's recursive iterators.

Recursive Directory Iterator

The RecursiveDirectoryIterator class allows you to traverse the directory structure recursively. Each iteration returns a new SplFileInfo object that represents a file or directory.

Recursive Iterator Iterator

The RecursiveIteratorIterator class wraps a RecursiveDirectoryIterator and provides a convenient way to traverse the directory tree, recursively visiting subdirectories.

Example Code

Here's an example code snippet that showcases how to use these iterators:

<code class="php">$main = "MainDirectory";
$di = new RecursiveDirectoryIterator($main, RecursiveDirectoryIterator::SKIP_DOTS);
$rii = new RecursiveIteratorIterator($di);

foreach ($rii as $filename => $file) {
    // Do something with each file
    echo "$filename - {$file->getSize()} bytes\n";
}</code>
Copy after login

This code initializes a RecursiveDirectoryIterator for the MainDirectory and skips the current and parent directories (. and ..). Then, it creates a RecursiveIteratorIterator and iterates over the directory tree. Each time it encounters a file, it echoes the filename and the file size.

Note: You can modify the do something with each file part to perform the desired operation on each file. This example simply prints the filename and size for each file.

The above is the detailed content of How to Recursively Read Subdirectories and Process Files in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template