有人能帮我吗?
我有一个文件夹,里面有一些文件(没有扩展)
/模块/邮件/模板
使用这些文件:
我想首先循环并读取文件名(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
}
发布于 2012-08-05 01:30:01
这段代码适用于我:
<?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-05 01:04:05
在循环之外初始化数组。然后在循环中分配它的值。不要尝试打印数组,直到你在循环之外。
调用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);
https://stackoverflow.com/questions/11813165
复制相似问题