2012-08-05 61 views
1

有人可以帮助我吗?PHP forech循环读取文件,创建数组和打印文件名

我有一些文件(无extention)

/模块/邮件/模板

随着这些文件的文件夹:

  • 测试
  • test2的

我想先循环并读取文件名(test和test2)并将它们打印到我的ht中毫升表格作为下拉项目。这是有效的(表单html标签的其余部分在上面和下面的代码下面,这里省略)。

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

这是我如何努力实现这一目标,没有运气:

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 
     } 

任何帮助,将不胜感激:)

+0

什么错?解释你的意思是“不工作” – SomeKittens 2012-08-05 01:00:12

+0

var_dump($ templateName);就在你的循环的顶部。我的猜测是glob()没有拾取具有该模式的任何文件。 – 2012-08-05 01:03:27

+0

循环运行但不会回显$ content var,并且print_r不会打印。所以我认为它没有回应,或者我做错了什么。也许有更好的方法来做到这一点。但是我不知道它出错的地方,因为它只是没有错误地运行,但不会做我想要的。 – Bolli 2012-08-05 01:04:23

回答

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

感谢它为我工作 – Bolli 2012-08-05 01:32:24

1

初始化循环外的数组。然后在循环内分配它的值。不要尝试打印阵列,直到您处于循环之外。

拨打file_get_contents时出现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); 
+0

'file_get_contents'中的'r'会来自['fopen'](http://php.net/manual/en/function.fopen.php)。 – 2012-08-05 01:12:21

+0

对不起,我开始使用fopen,并忘记改变它。 非常感谢您的帮助。现在我再次获得文件名,但仍然没有print_r和echo $ content的输出 – Bolli 2012-08-05 01:20:36

+0

此外,使用'echo' ';'或'echo“”;'。 – 2012-08-05 01:21:14