I'm receiving a JSON string dynamically, which looks like:
{ "post": [ { "id": "11", "body": "", "image": "images/rose.png", "stamp": "2013-11-04 14:50:11" } ] }
I'm trying to pretty-print this JSON string as follows:
{
    "post": [
        {
            "id": "11",
            "body": "",
            "image": "images/rose.png",
            "stamp": "2013-11-04 14:50:11"
        }
    ]
}
So, I tried the following code (just for demonstration purposes):
<?php
$str = '{ "post": [ { "id": "11", "body": "", "image": "images\/rose.png", "stamp": "2013-11-04 14:50:11" } ] }';
$obj = json_decode($str);
echo json_encode($obj, JSON_PRETTY_PRINT);
And it just outputs the unformatted JSON string:
{ "post": [ { "id": "11", "body": "", "image": "images/rose.png", "stamp": "2013-11-04 14:50:11" } ] }
But when I add the following line above my json_encode() statement, it works as expected. 
header('Content-Type: text/plain');
What could be causing this issue? Why is it not working when the Content-Type is text/html?
JSON_PRETTY_PRINT uses whitespace to format the JSON. When this is displayed as HTML the whitespace is ignored. If you want to keep the formatting then wrap the JSON in <pre> tags.
For example:
<?php
$str = '{ "post": [ { "id": "11", "body": "", "image": "images\/rose.png", "stamp": "2013-11-04 14:50:11" } ] }';
$obj = json_decode($str);
$json = json_encode($obj, JSON_PRETTY_PRINT);
printf("<pre>%s</pre>", $json);
If you don't want to use <pre> tags then you can also use the CSS property, white-space: pre on whatever element the JSON is contained in. 
You use this header:
header('Content-Type: application/json; charset=utf-8');
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With