将PHP数据作为JSON对象返回

时间:2015-11-09 09:57:13

标签: javascript php json getjson

我有一个PHP脚本,必须为包含在特定目录中的所有文件返回3个内容。

  1. 文件名
  2. 文件大小
  3. Filecreation time
  4. 我能够为每个文件回显这三个值,但我想以JSON格式返回所有这些数据。将所有这些数据转换为JSON格式的最佳方法是什么?

    function listAllFiles($dir)
    {
        $format = "d/m/y h:m";
        $filesInfo;
        if (is_dir($dir))
       {
            if ($dh = opendir($dir))
            {
                while (($file = readdir($dh)) !== false)
               {
                   if ($file != "." && $file != "..") 
                   {   
                       echo findFileSize($dir.'/'.$file)."      ".date($format, filemtime($dir.'/'.$file))."     ";
                       echo $file.'<br>';
    
                   }     
    
               } 
             }
         closedir($dh);
    
    
       }
        else {
           print 'folder not found';
        }
    }
    

2 个答案:

答案 0 :(得分:1)

<强>功能

  
      
  1. 文件名
  2.   

Use glob() to find the files in a directory

  
      
  1. 文件大小
  2.   

Use filesize() to find the size of a file

  
      
  1. Filecreation time
  2.   

Use filectime() to find the last creation time of a file

  

将所有这些数据转换为JSON格式的最佳方法是什么?

Use json_encode() to convert a PHP array to a JSON array

代码示例

function listAllFiles($dir){
    if(!isdir($dir)) { print "Folder not found"; return; }

    $files = glob($dir);
    $arr = array();
    foreach($files as $file){
        $file = array();

        //Get filename
        $file["name"] = $file;

        //Get filesize
        $file["size"]= filesize($file);

        //Get file creation time
        $file["creation_time"] = filectime($file);

        array_push($arr, $file);
    }

    $json = json_encode($arr);
    return $json;
}

echo listAllFiles("/folder/");

答案 1 :(得分:0)

PHP json_encode()json_decode()

中有2个简单的json函数

json_encode()将PHP数组或对象转换为JSON字符串,因此创建一个数组或对象以包含所有数据,然后将json_encode()的结果回显给调用应用程序。

function listAllFiles($dir) {

    $results = array();
    $results['error'] = false;

    $format = "d/m/y h:m";
    $filesInfo;
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
               if ($file != "." && $file != "..") {   

                   // create an object to hold data for this file
                   $o = new stdClass();
                   $o->filesize = findFileSize($dir.'/'.$file)
                   $o->filedate = date($format, filemtime($dir.'/'.$file));
                   $o->filename = $file;

                   // put this object into the results array
                   $results[] = $o;
               }     
            } 
        }
        closedir($dh);
   } else {
       $results['error'] = true;
       $results['err_msg'] = 'folder not found';
    }

    return $results;
}


$result = listAllFiles('a/b/c');
echo json_encode($result);