Bejkrools
Bejkrools

Reputation: 1157

Write JSON to txt file with formatting

I have content in JSON format. For instance:

{"rand":"7542868","action":"get","identity":{"name":"Jack","password":"secret"},"key":"o8sh769f79"} and i know how to decode it. But how to put in into txt file as pretty-formatted like following?

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

PHP Version 5.5.27

I created method:

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

input $type equals <- and $data is {"rand":"7542868","action":"get","identity":{"name":"Jack","password":"secret"},"key":"o8sh769f79"}

but output file is

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

still inline.

Upvotes: 1

Views: 3424

Answers (1)

Franz Gleichmann
Franz Gleichmann

Reputation: 3579

$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

Upvotes: 4

Related Questions