Search code examples
phpoopiteratordirectory-structurespl

Building A Log Reader with PHP RecursiveTreeIterator


I have this dir structure for logs

logs
-2012
--01
---01.php
---02.php
--02
---20.php
---23.php

I want to be able to use PHP's RecursiveTreeIterator to be able to display a tree having actual php files(not dirs) as links to display the file contents.

Using the first answer in this question as a guide: Sorting files per directory using SPL's DirectoryTreeIterator

I am new to most of PHP 5's SPL so I need some help here. How do I build the tree? Thanks!


Solution

  • As an alternative to the links I provided in the comments already:

    you can also extend the TreeIterator's current() method to provide additional markup:

    class LinkedRecursiveTreeIterator extends RecursiveTreeIterator
    {
        public function current()
        {
            return str_replace(
                $this->getInnerIterator()->current(),
                sprintf(
                    '<a href="%1$s">%1$s</a>',
                    $this->getInnerIterator()->current()
                ),
                parent::current()
            );
        }
    }
    
    $treeIterator = new LinkedRecursiveTreeIterator(
        new RecursiveDirectoryIterator('/path/to/dir'),
        LinkedRecursiveTreeIterator::LEAVES_ONLY);
    
    foreach($treeIterator as $val) echo $val, PHP_EOL;
    

    The above will print the regular ASCII tree the TreeIterator prints but will wrap the filename into hyperlinks. Note that $this->getInnerIterator()->current() returns File objects, so you can access any other file properties, like filesize, last modified, etc, as well.