【问题标题】:How to loop through files in a directory and output the contents of each file in a <div> [duplicate]如何遍历目录中的文件并在 <div> 中输出每个文件的内容 [重复]
【发布时间】:2012-06-23 23:50:42
【问题描述】:

可能重复:
Loop code for each file in a directory

我认为我可以使用以下代码达到此目的,但我认为我在此代码include($file[$]) 中犯了一些错误@

<?php
$dir= opendir(".") or die ('Cannot open directory');
$div="<div class=\"left1\">\n";
echo "<div class=\"wrapper\">\n";
for( $i=0; $i<6; $i++){
    while(($file = readdir($dir)) != false){
    if(preg_match("/php$/", $file)){
    echo $div;
    include($file[$i]); // HERE ITS NOT WORKING AS I WANT
    echo "</div>\n";
    }
    }
}
echo "</div>\n";

?>

【问题讨论】:

  • 您尝试过 include_once 吗?
  • 尝试使用 echo 而不是 include 以确保 $file[$i] 符合您的预期。
  • @Fire-Dragon-DoL 我在您发表评论后使用,但结论与我的预期不符,但谢谢
  • @andrewsi 好的,我会记住的,谢谢
  • 文件的内容是什么?如果只是 HTML 内容,最好将其存储在数据库中并使用带有所见即所得编辑器的编辑页面来更新内容。

标签: php


【解决方案1】:

readdir 将实际文件名作为字符串返回,因此您尝试将该文件名作为一个数组访问,这将只提取该文件名的一个字符。

试试:

include($file);

相反。除此之外,不需要opendir/readdir,你可以使用glob()

$phpfiles = glob('*.php');
foreach($phpfiles as $file) {
    include($file);
}

【讨论】:

  • +1 glob() 是这里的最佳选择。
  • 好的,谢谢我尝试将此代码集成到我的代码中,它看起来和我的一样复杂
【解决方案2】:

$file 此时是纯字符串,而不是数组。因此,您只需要include($file) 而不是include($file[$i])

while(($file = readdir($dir)) !== false){
  if(preg_match("/php$/", $file)){
      echo $div;
      include($file);
      echo "</div>\n";
   }
}

整个外部for 循环似乎是不必要的。

【讨论】:

  • 好的,谢谢迈克尔,它现在可以工作了 :)
  • 但我需要 6 个不同的 php 文件包含在 6 个 div 标签中,沿页面的水平方向,接下来 7. php 文件必须以相同的方式再次包含在不同的 6 er div 中组,这是我使用 for 循环的原因,我想我应该使用 foreach 也许 thx
  • @HilmiSleymanTunahanDemirkay 它是否使用for 循环实现了您想要的功能?如果我理解并且您想包含同一组文件 6 次,那么您将需要通过 closedir() 关闭目录句柄并在 for 循环的每个循环中使用 opendir() 重新打开它。
  • 不,它不符合我的要求,只是尝试一下,我认为您的建议让我更接近我的目标。
猜你喜欢
  • 1970-01-01
  • 2011-12-29
  • 2021-01-16
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
相关资源
最近更新 更多