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,526
  • 11
  • 62
  • 104

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
  • 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
  • Happy to have helped! – Amal Murali Feb 07 '14 at 16:29