尝试使用递归目录迭代器列出文件和文件夹

时间:2019-02-02 07:09:10

标签: php arrays json file scandir

我怎么了?

我正在尝试使用RecursiveDirectoryIterator函数代替Scandir,但没有得到所需的Json响应。

我知道这是一段很长的代码,但是我真的很想实现其他功能,例如directory permissions ,owner etc using iterator,如果有人可以看一下,我会非常感激。

$path = dirname(__DIR__).'/files';
$dirname = explode('/',$path);
$dirname = end($dirname);

扫描目录功能:

function scan($path,$dirname){
  $files = array();
  // Is there actually such a folder/file?
  if(file_exists($path)){
    foreach(scandir($path) as $f) {
      if(!$f || $f[0] == '.') {
        continue; // Ignore hidden files
      }
      $ext_to_exclude = array('php','html','.htacces');
      if(cmprExtension($f,$ext_to_exclude)) {
        continue; // Ignore some extensions
      }
      if(is_dir($path . '/' . $f)) {
        // The path is a folder
        $files[] = array(
          "name" => $f,
          "type" => "folder",
          "path" => $dirname.'/'.$f,
          "items" => scan($path.'/'.$f, $dirname.'/'.$f) // Recursively get the contents of the folder
        );
      }
      else {
        // It is a file
        $files[] = array(
          "name" => $f,
          "type" => "file",
          "path" => $dirname.'/'.$f,
          "size" => filesize($path.'/'.$f) // Gets the size of this file
        );
      }
    }
  }
    return $files;    
}

RecursiveDirectoryiterator功能:

function scanRDI($path){
        $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
        $files = array(); 
        foreach ($rii as $file){
          if($file->isDir()) {
            // The path is a folder
            $files[] = array(
              "name" => $file->getFilename(),
              "type" => "folder",
              "path" => $file->getPathname(),
             "items" => scanRDI($file->getPath())
            );
          }
          else {
            // It is a file
            $files[] = array(
              "name" => $file->getFilename(),
              "type" => "file",
              "path" => $file->getPathname(),
              "size" => $file->getSize()  // Gets the size of this file
            );
          }
        }
        return $files;
    }

Json Endoing:

    header('Content-type: application/json');

    echo json_encode(array(
      "name" => $dirname,
      "type" => "folder",
      "path" => $dirname,
      "items" => scan($path) OR scanRDI($path)
    )); 

Json响应:(在jsonviewer中将视图从右侧面板更改为代码)

  

对于Scandir:https://codebeautify.org/jsonviewer/cb94493e

     

对于RDI:https://codebeautify.org/jsonviewer/cb9e1297

0 个答案:

没有答案