I have JSON data in one line string. I want output it like structured source code, how can I do that in PHP?
Asked
Active
Viewed 264 times
0
-
[This can help](http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php) – lavrik Feb 07 '14 at 16:02
1 Answers
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"
}

Amal Murali
- 75,622
- 18
- 128
- 150
-
Thanks, it works, maybe you know how to do the same with XML data string? – Dmytro Zarezenko Feb 07 '14 at 16:06
-
@DmytroZarezenko: Load the XML using [DOMDocument](http://php.net/domdocument) class, set `$doc->preserveWhiteSpace = false; $dom->formatOutput = TRUE;`, and then `$formatted_output = $dom->saveXML();` - but that's an entirely different question and should be posted as such - [this post](http://stackoverflow.com/a/8615485/) should answer your question, though :) – Amal Murali Feb 07 '14 at 16:08
-