PHP - Read number of dirs and then require for each a specified file name

笑着哭i 提交于 2019-12-13 03:53:48

问题


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!


回答1:


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()).




回答2:


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



来源:https://stackoverflow.com/questions/2523839/php-read-number-of-dirs-and-then-require-for-each-a-specified-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!