Question

I want to make a little script but I'm rather n00b in php so please help me if you can :)

What I want the script to do is:

  1. I have "index.php".
  2. I want "index.php" to read the sub-directories from a known folder, let's say "templates/"
  3. Each sub-directory will contain a file called "content.html".
  4. The index will then load the "content.html" with the require() function for each of the existing sub-directories.

Thank you very much for your help!

Was it helpful?

Solution

The RecursiveDirectoryIterator runs through the designated directory and all subdirectories and returns all filesystem items as SplFileInfo objects:

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($yourFilePath));

foreach($iterator as $file) {
    if($file->getFilename() === 'content.html') {
        $file->openFile()->fpassthru();
        // or 
        include $file->getRealpath();
    }
}

Use include when you want to run the .html file through the PHP parser, e.g. when it contains PHP code that needs to be evaluated. If not, use fpassthru, because that should be a fraction faster. Can also use readfile($file->getRealpath()).

OTHER TIPS

what do you want to achieve?

Do you want the content of the different files in your index.php or do want to generate a link to these files?

Because if you want to aggregate the content, this approach is not enough because you get a html file with invalid syntax, because you simply concatenate the content of the html files.

You will need some additional parsing of the content to avoid this.

Cheers,

Dawit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top