Skip to content

Instantly share code, notes, and snippets.

@TechplexEngineer
Created April 29, 2015 05:13
Show Gist options
  • Select an option

  • Save TechplexEngineer/5381bfff9f511c4aa5db to your computer and use it in GitHub Desktop.

Select an option

Save TechplexEngineer/5381bfff9f511c4aa5db to your computer and use it in GitHub Desktop.
Generate a json string of files in a directory
<?php
header('Content-Type: application/json');
function scandir_folders($d, $blacklist = array('.', '..')) {
return array_filter(scandir($d), function ($f) use($d, $blacklist) {
return is_dir($d . DIRECTORY_SEPARATOR . $f) && !in_array($f, $blacklist);
});
}
function scandir_all($d, $blacklist = array('.', '..')) {
return array_filter(scandir($d), function ($f) use($d, $blacklist) {
return !in_array($f, $blacklist);
});
}
//@todo probably should limit the depth
function recurse_scandir($d, $first=false)
{
$out = "";
if (!$first) {
$out .= ",";
}
$out .= "{";
$cnt = 0;
foreach (scandir_all($d) as $key=>$item)
{
$path = $d.'/'.$item;
if (is_dir($path))
{
$out .= "\"$path\":";
$out .= recurse_scandir($path, true);
if ($cnt==0) {
$out .= ",";
}
}
else
{
if ($cnt && substr($out, -1)!=",") {
$out .= ",";
}
$out .= "\"$item\":\"$path\"";
}
$cnt++;
}
$out .= "}";
return $out;
}
echo recurse_scandir('./src', true);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment