PHP 扫描一个目录,对于找到的每个文件,在它自己的 DIV 元素中回显该文件的内容

PHP to scan a directory and, for every file found, echo the contents of that file within it's own DIV element

此代码显示服务器上文件夹中的文件列表:

<div>
  <?php
    if ($handle = opendir('../trx/assets/')) {
      while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
          echo $entry, '<br>';
        }
      }
    closedir($handle);
   }
  ?>
</div>

它returns:

test.txt 
banana.txt 
cheese.txt

并且此代码在 div

中显示其中一个文件的内容
<div>
<?php
   echo nl2br(file_get_contents( '../trx/assets/test.txt' ));
?>
</div>

目前我手动查看该文件夹并为每个文件创建一个 div 然后使用 php 回显其内容。由于“assets”文件夹中的文件是由用户创建的,我想做的是在页面加载时 PHP 使用这些文件的内容自动创建 divs。

我的想法是有一个 foreach 循环来读取目录,并为找到的每个文件创建一个 div 并回显其内容,但即使看了 [=15= 之后我也不知道该怎么做], 谁能帮忙?

如果我理解正确,您希望扫描一个目录,并且对于找到的每个文件,在它自己的 DIV 元素中回显该文件的内容,那么以下内容可能会有所帮助?下面是使用当前工作目录的子文件夹在本地测试的,简称为 textfiles

    #'../trx/assets/'
    $dir=sprintf('%s/textfiles',__DIR__);
    
    if ( $handle = opendir($dir) ) {
      while( false !== ( $entry = readdir( $handle ) ) ) {
        if( $entry != "." && $entry != ".." ) {
            
          printf(
            '<div><h1>%s</h1>%s</div>',
            $entry,
            nl2br( file_get_contents( sprintf( '%s/%s', $dir, $entry ) ) ) 
          );
        }
      }
      closedir($handle);
   }
}

以上不会递归到子目录 - 只是从指定的文件夹级别读取。愉快地递归到子文件夹到任何深度 recursiveDirectoryIterator 似乎合适。

用于递归所有子目录 a RecursiveIteratorIteratorRecursiveDirectoryIterator

$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir ), RecursiveIteratorIterator::SELF_FIRST );
if( is_object( $files ) ){
   foreach( $files as $name => $file ){
       if( !$file->isDir() && strtolower( pathinfo( $file->getFileName(),PATHINFO_EXTENSION ) )=='txt' ){
            printf(
                '<div><h1>%s</h1>%s</div>',
                $file->getFileName(),
                nl2br( file_get_contents( sprintf( '%s/%s', $dir, $file->getFileName() ) ) ) 
            );
       }
   }
}