Make a php json file which display first folder and next files in a directory + how to echo file extension
Get the solution ↓↓↓$dir = "../../";
if(is_dir($dir)){
if($dh = opendir($dir)){
while(($file = readdir($dh)) != false){
if($file != "." and $file != ".."){
$files_array[] = array('file' => $file);
}
}
}
sort($files_array);
$return_array =array('name_array' => $files_array);
echo json_encode($return_array);
}
header('Content-type: application/json');
How to make it ? There is my source code. I want to know how to sort it + how to echo file extension. Thx :)
Answer
Solution:
- header must be set before echo
- stop the cycle after recovering the first file, if you only want the first one. Or if you want the first in alphabetical order, return only the first element of the array to return less data. Check if exist first element of array.
- set the array empty in case the directory has no files
- check that the first result is not a directory, if you want a file
Sample:
header('Content-type: application/json'); # before echo
$dir = "../../";
$files_array=[]; # empty array
if(is_dir($dir)){
if($dh = opendir($dir)){
while(($file = readdir($dh)) != false){
if($file != "." and $file != ".."){
if(!is_dir($file)){ # check is not dir
$ext = '';
if(strpos($file,'.', 1)) {
$aExt = explode(".", $file);
# select last element for extension
$ext = $aExt[count($aExt)-1];
}
$files_array[] = array('file' => $file, 'ext'=> $ext );
break; # break while
}
}
}
}
# sort($files_array); # sort multiple file
# $return_array =array('name_array' => (isset($files_array[0]?$files_array[0]:[]))); # return only first element if exist
$return_array =array('name_array' => $files_array);
echo json_encode($return_array);
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: mark bundle as not supporting multiuse
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.