2

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!

9
  • 1
    if you just want to list the files, you dont need the treeIterator. The treeIterator is for printing an ASCII tree. Commented Feb 27, 2012 at 22:45
  • possible duplicate of ASCII Library for Creating "Pretty" Directory Trees? (remove the SELF_FIRST constant and it should list only the files/leaves) Commented Feb 27, 2012 at 22:46
  • should I rephrase that? I have tried different approaches, the link given and the DirectoryIterator approach. Gordon, is there not any way to retrieve file information from this ASCII tree, or it does just print? Commented Feb 27, 2012 at 22:48
  • @Ygam Like I said, the treeIterator will print an ASCII tree. So you cannot get at the iterated file in a foreach. However, you can use a for loop to iterate it and then access the iterated files by accessing the inner Iterator from the treeIterator. Commented Feb 27, 2012 at 22:53
  • I was asking that so that I can display the files as links that points to the file path Commented Feb 27, 2012 at 22:54

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this is it! had a hard time looking for a way to access file details as the documentation does not say much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.