首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP源程序读取文件,创建数组和打印文件名。

PHP源程序读取文件,创建数组和打印文件名。
EN

Stack Overflow用户
提问于 2012-08-05 00:58:09
回答 2查看 1.9K关注 0票数 1

有人能帮我吗?

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

/模块/邮件/模板

使用这些文件:

  • 测试
  • test2

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

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

这就是我如何努力做到这一点,没有运气:

代码语言:javascript
运行
复制
    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
        }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-05 01:30:01

这段代码适用于我:

代码语言:javascript
运行
复制
<?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);
?>
票数 1
EN

Stack Overflow用户

发布于 2012-08-05 01:04:05

在循环之外初始化数组。然后在循环中分配它的值。不要尝试打印数组,直到你在循环之外。

调用r中的file_get_contents是错误的。把它拿出来。file_get_contents的第二个参数是可选的,如果使用它,应该是布尔值。

检查file_get_contents()没有返回FALSE,这是它返回的内容,如果读取文件时出错的话。

您在引用$templatName而不是$templateName时有一个错误。

代码语言:javascript
运行
复制
$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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11813165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档