【问题标题】:include all files in folder and if empty show text包括文件夹中的所有文件,如果为空则显示文本
【发布时间】:2013-10-18 17:02:31
【问题描述】:

现在我使用以下代码将目录中的所有文件包含到我的站点中:

<?php   foreach (glob("overzicht/projects/*.php") as $filename)
{
 include $filename;
}
?>

但是当目录为空时,我希望他显示文本:“目录中没有找到文件。”

我该怎么做?

【问题讨论】:

    标签: php file include directory


    【解决方案1】:
    $listy = glob("overzicht/projects/*.php");
    if (empty($listy)) {
        echo "there are no files found in the directory";
    } else {
      foreach ($listy as $filename) {
        include $filename;
      }
    }
    

    【讨论】:

    • 我投了赞成票,但你应该把它改成if (!$listy || empty($listy)),根据手册,glob Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error. 注意: On some systems it is impossible to distinguish between empty match and an error.
    • @Peter 没关系。你是对的(有点,empty(false) 给你一个语法错误哈哈)。
    • @Peter,已更正。 PHP Ver
    【解决方案2】:
    <?php
        $flag = true;
        foreach (glob("overzicht/projects/*.php") as $filename)
        {
            include $filename;
            $flag = false;
        }
        if ($flag)
        {
            print("There are no files found in the directory.");
        }
    ?>
    

    我确信有更好的方法来做到这一点......但这已经足够了。

    【讨论】:

      【解决方案3】:

      将它们作为数组抓取,测试数组长度,如果大于零,则包含它们,否则显示消息,如下例所示:

      <?php
      $files = glob("overzicht/projects/*.php");
      if (count($files) == 0)
      {
          echo "There are no files found in the directory";
      }
      else
      {
          foreach($files as $file)
          {
              include $file;
          }
      }
      ?>
      

      【讨论】:

      • glob 的结果是一个数组
      • @Peter 我以前没有使用过 glob,所以我没有意识到这一点。已相应地修改了我的代码
      【解决方案4】:

      $`files = glob("overzicht/projects/*.php"); foreach (`$`files as $filename) { 如果(文件存在(`$`文件名)){ 包含一次`$`文件名; } 别的 { echo '目录下没有文件。\n'; } } ?> 如果您的目录中有很多文件。试试这个......我希望它会出现

      【讨论】:

        【解决方案5】:

        添加标志以检测是否找到文件。

        <?php   
        $found = false;
        foreach (glob("overzicht/projects/*.php") as $filename)
        {
            if(file_exists($filename)) {
                include $filename;
                $found = true;
            }
        }
        
        if(!$found) {
            print("There are no files found in the directory.")
        }
        ?>
        

        【讨论】:

        • if(file_exists($filename)) { 的有趣用法。你能给我们举个例子,glob 找到了一些文件但它不存在吗?
        • @Peter 脑放屁的经典例子。我习惯于在包含之前使用它来检测文件。出于某种原因,我认为通过在循环中简单地设置$found = true 可能会错误地设置标志而没有进行文件检查。我的错...
        猜你喜欢
        • 2013-07-11
        • 1970-01-01
        • 2022-11-10
        • 1970-01-01
        • 2019-03-31
        • 2020-07-11
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多