Created
July 20, 2023 14:52
-
-
Save Silloky/650532cb2434e99fb754cdad15173208 to your computer and use it in GitHub Desktop.
PHP : get recursive directory structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getContents($path) { | |
$contents = array_diff(scandir($path, SCANDIR_SORT_ASCENDING), array('..', '.')); // For Linux environments, excluded the .. and . from list | |
$filtered = array(); | |
foreach ($contents as $item) { | |
$itemPath = $path . '/' . $item; // scan_dir() requires an entire path, not just the filename (unless you cd in the directory) | |
if (is_dir($itemPath)){ // only keeps the directories | |
$subarray = array('name' => "$item", 'children' => getContents($itemPath)); // saves the folder name as `name` property and the children recursively | |
array_push($filtered, $subarray); | |
} | |
} | |
return $filtered; | |
} | |
$rootDir = '/path/to/analysis/root/directory/'; | |
$structure = json_encode(getContents($rootDir), JSON_PRETTY_PRINT); | |
header('Content-Type: application/json'); # tells your browser it's receiving json data | |
echo $structure; # send the json to your browser |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment