Search code examples
phpforeachfile-get-contents

PHP foreach loop read files, create array and print file name


Could someone help me with this?

I have a folder with some files (without extention)

/module/mail/templates

With these files:

  • test
  • test2

I want to first loop and read the file names (test and test2) and print them to my html form as dropdown items. This works (the rest of the form html tags are above and under the code below, and omitted here).

But I also want to read each files content and assign the content to a var $content and place it in an array I can use later.

This is how I try to achieve this, without luck:

    foreach (glob("module/mail/templates/*") as $templateName)
        {
            $i++;
            $content = file_get_contents($templateName, r); // This is not working
            echo "<p>" . $content . "</p>"; // this is not working
            $tpl = str_replace('module/mail/templates/', '', $templatName);
            $tplarray = array($tpl => $content); // not working
            echo "<option id=\"".$i."\">". $tpl . "</option>";
            print_r($tplarray);//not working
        }

Solution

  • This code worked for me:

    <?php
    $tplarray = array();
    $i = 0;
    echo '<select>';
    foreach(glob('module/mail/templates/*') as $templateName) {
        $content = file_get_contents($templateName); 
        if ($content !== false) {
            $tpl = str_replace('module/mail/templates/', '', $templateName);
            $tplarray[$tpl] = $content; 
            echo "<option id=\"$i\">$tpl</option>" . PHP_EOL;
        } else {
            trigger_error("Cannot read $templateName");
        } 
        $i++;
    }
    echo '</select>';
    print_r($tplarray);
    ?>