-2


I try to echo whole content of every html file in specific directory.

I know that i can use readfile() to read and return content of specific file. How can i use it with every html file in specific directory ?

Thank you for your help !

Ganga
  • 787
  • 1
  • 9
  • 27

2 Answers2

0

You could store the content of the files with file_get_contents().

This function (inspired by this answer) will return either a 2D array where $key => $value pairs are represented by $filename => $file_content or false if it fails to open the directory.

<?php
function read_htmlfiles_in_dir($dir)
{
    $files = array();
    if ($handle = opendir('.')) {
        while (false !== ($file = readdir($handle)))
        {
            if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'html')
            {
                $files[$file] = file_get_contents($file);
            }
        }
        closedir($handle);
        return ($files);
    }
    else
    {
        return (false);
    }
}
?>

include this somewhere then you can to this for example if you need to echo all the html files in the curent directory :

<?php
if ($htmlfiles = read_htmlfiles_in_dir('.'))
{
    foreach($htmlfiles as $file)
    {
        echo $file;
    }
}
?>

of you need a little debug you just

print_r($htmlfiles);

and get something like

Array
(
    [filename.html] => <div>Some HTML Code</div>
    [otherfile.html] => <span>Some <b>other</b> HTML code</span>

)

You will however have one last thing to think about : the order in which the HTML files have to be displayed.

Community
  • 1
  • 1
Mouradif
  • 2,666
  • 1
  • 20
  • 37
0

or you could do somrthing much simpler..

$FILES = scandir("/complete/path/to/directory");
foreach($FILES as $FILE)
    if($FILE == "." || $FILE == "..") continue;
    else include($FILE);

if it's the current directory..

$FILES = scandir(realpath(dirname(__FILE__)));
foreach($FILES as $FILE)
        if($FILE == "." || $FILE == ".." || $FILE ==  __FILE__) continue;
        else include($FILE);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116