0
我有JSON格式的內容。例如:將JSON寫入帶格式的txt文件
{"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);
}
輸入$型等於<-
和$數據是 {"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\"}"
仍然在線。
或許應當指出的是,這個常數'JSON_PRETTY_PRINT'僅在PHP版本5.4起可用! (從手冊:'JSON_PRETTY_PRINT(integer) 在返回的數據中使用空格來格式化它。自PHP 5.4.0起可用。) – RamRaider
您必須將PHP數組傳遞給json_encode,而不是已編碼的JSON字符串。否則,你必須先解碼它:json_encode(json_decode($ data),JSON_PRETTY_PRINT); –