list files php from - create json file

前端 未结 2 623
情话喂你
情话喂你 2021-01-24 10:55

I want to create a php script that loads all my files (.pdf) from the 3 directory and create a json file.

I try this

$dir_2016 = \"./HCL/2016\";
$dir_201         


        
相关标签:
2条回答
  • 2021-01-24 11:04

    You should move your definition of $json_file to bottom as follow:

    // ... get files code
    $json_file = array(
        "2016" => $files_2016,
        "2015" => $files_2015,
        "2014" => $files_2014,
    );
    echo json_encode($json_file);
    

    Because array is passing by value rather than passing by reference.

    And, a better way to get files and sub-directories in a directory shallowly is use scandir, for example:

    $files_2014 = array_slice(scandir('./HCL/files_2014'), 2)
    

    See: http://php.net/manual/en/function.scandir.php

    0 讨论(0)
  • 2021-01-24 11:21

    Building on my comment above, here's a cheap way to get only pdf-filenames in the given directories:

    <?php
    header('Content-Type: application/json; charset="utf-8"');
    
    $dirs = [
        './HCL/2016',
        './HCL/2015',
        './HCL/2014',
    ];
    
    $files = [];
    
    foreach ($dirs as $dir) {
        if (is_dir($dir)) {
            $files[basename($dir)] = glob($dir . '/*.pdf');
        }
    }
    
    array_walk_recursive($files, function (&$entry) {
        $entry = basename($entry);
    });
    
    echo json_encode($files, JSON_PRETTY_PRINT);
    

    Note that there's a multitude of other ways of how to get all files in a directory, so this is by no means the only solution.

    0 讨论(0)
提交回复
热议问题