I'm building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode
. Here is an example script:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
The above code yields the following output:
{"a":"apple","b":"banana","c":"catnip"}
This is great if you have a small amount of data, but I'd prefer something along these lines:
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.
Many users suggested that you use
Which is absolutely right. But it's not enough, the browser needs to understand the type of data, you can specify the header just before echo-ing the data back to the user.
This will result in a well formatted output.
Or, if you like extensions you can use JSONView for Chrome.
1 -
json_encode($rows,JSON_PRETTY_PRINT);
returns prettified data with newline characters. This is helpful for command line input, but as you've discovered doesn't look as pretty within the browser. The browser will accept the newlines as the source (and thus, viewing the page source will indeed show the pretty JSON), but they aren't used to format the output in browsers. Browsers require HTML.2 - use this fuction github
If you have existing JSON (
$ugly_json
)Have color full output: Tiny Solution
Code:
This solution makes 'really pretty' JSON. Not exactly what the OP was asking for, but it lets you visualise the JSON better.
}
I had the same issue.
Anyway I just used the json formatting code here:
http://recursive-design.com/blog/2008/03/11/format-json-with-php/
Works well for what I needed it for.
And a more maintained version: https://github.com/GerHobbelt/nicejson-php