代码之家  ›  专栏  ›  技术社区  ›  Bolli

PHP foreach循环读取文件,创建数组并打印文件名

  •  1
  • Bolli  · 技术社区  · 12 年前

    有人能帮我吗?

    我有一个文件夹,里面有一些文件(没有扩展名)

    /模块/邮件/模板

    使用这些文件:

    • 测验
    • 测试2

    我想首先循环并读取文件名(test和test2),并将它们作为下拉项打印到我的html表单中。这是可行的(表单html标记的其余部分位于下面代码的上方和下方,此处省略)。

    但我也想读取每个文件的内容,并将内容分配给var$content,然后将其放置在以后可以使用的数组中。

    这就是我努力实现这一目标的方式,但没有运气:

        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
            }
    
    2 回复  |  直到 12 年前
        1
  •  1
  •   uınbɐɥs Alex Reynolds    12 年前

    这个代码对我有效:

    <?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);
    ?>
    
        2
  •  1
  •   Trott    12 年前

    初始化循环外的数组。然后在循环中为其赋值。在循环之外之前,不要尝试打印数组。

    这个 r 在对的呼叫中 file_get_contents 是错误的。把它拿出来。的第二个论点 文件集内容 是可选的,如果使用它,则应为布尔值。

    检查一下 file_get_contents() 没有返回 FALSE 如果在尝试读取文件时出现错误,则返回该值。

    你所指的地方有一个拼写错误 $templatName 而不是 $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);