1

有人可以帮我解决这个问题吗?

我有一个包含一些文件的文件夹(没有扩展名)

/模块/邮件/模板

使用这些文件:

  • 测试
  • 测试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
        }
4

2 回答 2

1

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

r调用中的file_get_contents错误。把它拿出来。第二个参数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);
于 2012-08-05T01:04:05.403 回答
1

这段代码对我有用:

<?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);
?>
于 2012-08-05T01:30:01.710 回答