使用格式

时间:2016-01-20 10:21:53

标签: php json formatting

我有JSON格式的内容。例如:

{"rand":"7542868","action":"get","identity":{"name":"Jack","password":"secret"},"key":"o8sh769f79"}我知道如何解码它。但是如何将txt文件放入格式如下的格式?

{
  "rand":"7542868",
  "action":"get",
  "identity":
  {
    "name":"Jack",
    "password":"secret"
  },
  "key":"o8sh769f79"
}

PHP版本5.5.27

我创建了方法:

static function ApiLog($type ,$data)
    {
        $data = json_encode($data, JSON_PRETTY_PRINT);
        $myfile = fopen(__DIR__."/log/".date('Y-m-d').".txt", "w") or die("Unable to open file!");
        $entry = date("H:i:s")." ".$type." ".$data."\n";
        fwrite($myfile, $entry);
        fclose($myfile);
    }

输入 $ type 等于<- $ data {"rand":"7542868","action":"get","identity":{"name":"Jack","password":"secret"},"key":"o8sh769f79"}

输出文件是

11:34:23 <- "{\"rand\":\"7542868\",\"action\":\"get\",\"identity\":{\"name\":\"Jack\",\"password\":\"secret\"},\"key\":\"o8sh769f79\"}"

仍然是内联。

1 个答案:

答案 0 :(得分:2)

$file = fopen("yourfile.txt","w");
fwrite($file, json_encode($data_array, JSON_PRETTY_PRINT));
fclose($file);

http://php.net/manual/de/function.json-encode.php