Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON_PRETTY_PRINT not working as expected when Content-Type is HTML

Tags:

json

sql

php

mysql

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?

like image 632
Toshi Avatar asked Nov 17 '13 15:11

Toshi


2 Answers

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.

like image 192
Tomdarkness Avatar answered Oct 11 '22 18:10

Tomdarkness


You use this header:

header('Content-Type: application/json; charset=utf-8');
like image 40
Mixcoatl Avatar answered Oct 11 '22 17:10

Mixcoatl