PHP Get All File Paths by Extension (JSON, TXT, etc.) List View or Folder Tree Representation

Have you ever stared at a huge folder structure filled with all kinds of files — .json, .txt, .xml, maybe even some logs - and wished there was a quick way to just get all of them listed? You're not alone.

Whether you're a developer building a content manager, a data wrangler scraping through archives, or just a curious coder trying to understand what’s inside a project directory, this small PHP trick could save you hours.

Today, let’s walk through a powerful little PHP script that can:

  • List all files of a certain extension (like JSON, TXT, etc.)
  • Show them in a clean flat list
  • Or (if you're fancy) display them like a folder tree!

Why This Matters

I once had to clean up a large nested folder with hundreds of .json files — logs from a server running for years. Manually checking folders was frustrating. And that’s when I realized how much power lives in just a few lines of PHP.

That pain gave birth to this script.

What You'll Learn

By the end of this post, you'll know how to:

  • Recursively scan directories
  • Filter files by extension
  • Print file paths as a flat list or tree view
  • Easily customize the output to your needs

The Code – Clean and Simple

Let’s dive in. Here's the basic version that lists .json and .txt files:
$path = 'tren/musi/unit';
$rii = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS)
);

foreach ($rii as $file) {
    if ($file->isFile() && $file->getExtension() === 'json') {
        echo $file->getPathname() . PHP_EOL;
    }
}


Output Example (Tree View):

📂 Scanning directory: tren/musi/unit


📁 2025

  📄 data1.json

  📄 readme.txt

📁 2024

  📄 config.json


Customize It!

You can tweak this script to:

  • Search only recent files (filemtime)
  • Ignore certain folders
  • Log results to a file
  • Output in JSON or HTML

Let me know if you'd like help expanding it for those features!

Real-World Use Cases

  • Building file browsers in admin dashboards
  • Preparing data for import/export
  • Backing up specific file types
  • Debugging what’s inside messy folder structures


Final Thoughts

Sometimes, the best solutions are simple. This PHP script is one of those tools I keep in my toolbox — it helps me explore, clean up, and make sense of digital chaos.

So the next time you're buried under a pile of files and need to dig out just the useful ones, remember: a few lines of PHP can be your flashlight.

Found this helpful?

If you'd like me to turn this into a downloadable tool or make a web interface for it, drop a message or comment below. Happy coding!

Previous Post Next Post