Skip to content

Instantly share code, notes, and snippets.

@Silloky
Created July 20, 2023 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Silloky/650532cb2434e99fb754cdad15173208 to your computer and use it in GitHub Desktop.
Save Silloky/650532cb2434e99fb754cdad15173208 to your computer and use it in GitHub Desktop.
PHP : get recursive directory structure
<?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