return PHP 数据作为 JSON 对象

return PHP data as JSON Object

我有一个 PHP 脚本,它必须 return 为特定目录中包含的所有文件做 3 件事。

  1. 文件名
  2. 文件大小
  3. 文件创建时间

我可以为每个文件回显这三个值,但我想 return 所有这些数据都采用 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';
    }
}

函数

  1. filename

Use glob() to find the files in a directory

  1. filesize

Use filesize() to find the size of a file

  1. Filecreation time

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

What is the best way to convert all this data into JSON format?

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/");

PHP json_encode()json_decode()

中有 2 个简单的 json 函数

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

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);