0

I have JSON data in one line string. I want output it like structured source code, how can I do that in PHP?

Dmytro Zarezenko
  • 10,308
  • 9
  • 56
  • 99

1 Answers1

2

Use JSON_PRETTY_PRINT flag (PHP 5.4+):

$json_str = json_encode($data, JSON_PRETTY_PRINT);

Since you're having a JSON-string, you can first decode it into an object, and then re-encode it.

Example:

$str = '{"name":"John","age":"12","Location":"U.S.A"}';
echo json_encode(json_decode($str), JSON_PRETTY_PRINT);

Output:

{
    "name": "John",
    "age": "12",
    "Location": "U.S.A"
}

Demo

Amal Murali
  • 73,160
  • 18
  • 123
  • 143