列出目录上的文件并将结果打印为JSON [英] List Files on Directory and Print result as JSON
本文介绍了列出目录上的文件并将结果打印为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对不起,如果我的问题很简单,因为我不熟悉php和json.我已经创建了一个php文件,该文件列出了服务器上的目录,并且应将结果打印为JSON.那么,我该怎么办呢?
Sorry if my question is basic, because I dont familiar with php and json. I have create a php file that list a directory on my server and should print the result as JSON. So, how can I do that?
这是我的代码,用于列出目录中的文件:
Here is my code to list files on directory:
<?php
$dir = "picture/";
if(is_dir($dir)){
if($dh = opendir($dir)){
while(($file = readdir($dh)) != false){
if($file == "." or $file == ".."){
} else {
echo $file."<br />";
//echo json_encode($file);
}
}
}
}
?>
感谢您的回复....
推荐答案
我修改了Francisco的代码:
I modified Francisco's code:
<?php
header('Content-Type: application/json');
$dir = "./"; //path
$list = array(); //main array
if(is_dir($dir)){
if($dh = opendir($dir)){
while(($file = readdir($dh)) != false){
if($file == "." or $file == ".."){
//...
} else { //create object with two fields
$list3 = array(
'file' => $file,
'size' => filesize($file));
array_push($list, $list3);
}
}
}
$return_array = array('files'=> $list);
echo json_encode($return_array);
}
?>
结果:
{
"files": [{
"file": "element1.txt",
"size": 10
}, {
"file": "element2.txt",
"size": 10
}
]
}
这篇关于列出目录上的文件并将结果打印为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文