首页 > 解决方案 > 使用 json 和 php 显示每个文件夹中的文件

问题描述

我有一个使用 PHP 和 JSON 显示文件列表和一些详细信息的 Web 应用程序,我想更改我的代码 si 我可以显示每个文件夹中的所有文件

对于我之前的代码,文件位于文件夹中。所以我想列出/files/folder1、/files/folder2、/files/folder3、...等所有文件

这是我的代码:

<?php

$dir = "files";

// Run the recursive function    
$response = scan($dir);

// This function scans the files folder recursively, and builds a large array

function scan($dir){
    $files = array();
    // Is there actually such a folder/file?
    if(file_exists($dir)){
        foreach(scandir($dir) as $f) {
            if(!$f || $f[0] == '.') {
                continue; // Ignore hidden files
            }

            if(is_dir($dir . '/' . $f)) {
                // The path is a folder
                $files[] = array(
                    "name" =>$f,
                    "type" => "folder",
                    "path" => $dir . '/' . $f,
                    "items" => scan($dir . '/' . $f) // Recursively get the contents of the folder
                );
            } else {
                // It is a file
                $files[] = array(
                    "name" => $f,
                    "type" => "file",
                    "path" => $dir . '/' . $f,
                    "size" => filesize($dir . '/' . $f) // Gets the size of this file
                );
            }
        }
    }

    return $files;
}

// Output the directory listing as JSON

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

echo json_encode(array(
                    "name" =>; "files",
                    "type" =>; "folder",
                    "path" =>; $dir,
                    "items" =>; $response
                    )
        );

这是应用一些样式后的样子: 在此处输入图像描述

标签: phpjson

解决方案


这可能会帮助您:

<?php  
$dir = "/var/www/html/cntpanel";    

function scan($dir){ 
   $result = array(); 
   foreach(scandir($dir) as $key => $value){ 
      if(!empty($value) and !in_array($value, array(".", ".."))){ 
         if(is_dir($dir.DIRECTORY_SEPARATOR.$value)){ 
            $result[$value] = scan($dir.DIRECTORY_SEPARATOR.$value); 
         } 
         else{ 
            $result[] = $value; 
         } 
      } 
   }  
   return $result; 
} 

echo json_encode((array)scan($dir), JSON_UNESCAPED_UNICODE);

推荐阅读