Skip to content

Instantly share code, notes, and snippets.

@vrkansagara
Last active September 5, 2020 04:12
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 vrkansagara/f5cbb2e17930370457a01f20baf93545 to your computer and use it in GitHub Desktop.
Save vrkansagara/f5cbb2e17930370457a01f20baf93545 to your computer and use it in GitHub Desktop.
PHP Array Tree from given directory path.
<?php
declare(strict_types=1);
date_default_timezone_set('UTC');
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set("display_startup_errors", '1');
ini_set("log_errors", '1');
chdir(dirname(__DIR__));
function buildTree($path,array $skipExtension = [], array $skipDirectory = []){
$objectList = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
$directoryStructure = [];
foreach ($objectList->getInnerIterator() as $key => $objectIterator){
// Read Write Execute
$isReadable = $objectIterator->isReadable();
$isWritable = $objectIterator->isWritable();
$isExecutable = $objectIterator->isExecutable();
// File Info
// $getGroup = $objectIterator->getGroup(); // www-data
// $getOwner = $objectIterator->getOwner(); // $USER
$getType = $objectIterator->getType(); // file, dir
$getSize = $objectIterator->getSize(); // The filesize in bytes.
// $getPath = $objectIterator->getPath(); // TReturns the target of the filesystem link.
$isDirectory = $objectIterator->isDir();
$isFile = $objectIterator->isFile();
$fileName = $objectIterator->getFileName();// xyz.zip , 123.jpeg
$getExtension = $objectIterator->getExtension(); // zip, jpeg
// $getPath = $objectIterator->getPath(); // Absolute path
$getRealPath = $objectIterator->getRealPath(); // Absolute path
if (!$isReadable){continue;}
if (!empty($getExtension) && in_array($getExtension,$skipExtension)){continue;}
if($isDirectory && in_array($fileName,$skipDirectory)){continue;}
if($isReadable && $isDirectory && ! ($fileName == '..' || $fileName == '.')){
$directoryStructure[] = [
'name' =>$fileName,
'type' =>$getType,
'children' =>buildTree($getRealPath,$skipExtension)
];
}elseif($isFile){
$directoryStructure[] = [
'name' =>$fileName,
'type' =>$getType,
'size' =>$getSize,
'extension' =>$getExtension,
];
}
}
return $directoryStructure;
}
$path =__DIR__.'/';
$skipExtensionList = ['json','xml'];
$skipDirectoryList = ['.git','vendor','node_modules'];
$directoryStructure = buildTree($path,$skipExtensionList,$skipDirectoryList);
header("Content-type:application/json");
echo json_encode($directoryStructure);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment