Bolli
Bolli

Reputation: 5274

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:

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
        }

Upvotes: 1

Views: 1939

Answers (2)

uınbɐɥs
uınbɐɥs

Reputation: 7341

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);
?>

Upvotes: 1

Trott
Trott

Reputation: 70065

Initialize the array outside of the loop. Then assign it values inside the loop. Don't try to print the array until you are outside of the loop.

The r in the call to file_get_contents is wrong. Take it out. The second argument to file_get_contents is optional and should be a boolean if it is used.

Check that file_get_contents() doesn't return FALSE which is what it returns if there is an error trying to read the file.

You have a typo where you are referring to $templatName rather than $templateName.

$tplarray = array();
foreach (glob("module/mail/templates/*") as $templateName) {
        $i++;
        $content = file_get_contents($templateName); 
        if ($content !== FALSE) {
            echo "<p>" . $content . "</p>";
        } else {
            trigger_error("file_get_contents() failed for file $templateName");
        } 
        $tpl = str_replace('module/mail/templates/', '', $templateName);
        $tplarray[$tpl] = $content; 
        echo "<option id=\"".$i."\">". $tpl . "</option>";
}
print_r($tplarray);

Upvotes: 1

Related Questions