PHP JSON – Why the Code is Not Printing in Pretty JSON Format?

jsonphp

Here is my code:

<?php
$result = dns_get_record("php.net",DNS_ANY);

echo json_encode(array('data' => $result), JSON_PRETTY_PRINT);
?>

I am trying to print the output into pretty json format, but do not understand why it is not printing pretty json.
Here is the output I get after every attempt:

{ "data": [ { "host": "php.net", "class": "IN", "ttl": 30, "type": "MX", "pri": 0, "target": "php-smtp2.php.net" }, { "host": "php.net", "class": "IN", "ttl": 300, "type": "TXT", "txt": "v=spf1 ip4:72.52.91.12 ip6:2a02:cb41::8 ip4:140.211.15.143 ?all", "entries": [ "v=spf1 ip4:72.52.91.12 ip6:2a02:cb41::8 ip4:140.211.15.143 ?all" ] }, { "host": "php.net", "class": "IN", "ttl": 300, "type": "SOA", "mname": "ns1.php.net", "rname": "admin.easydns.com", "serial": 1484930803, "refresh": 16384, "retry": 2048, "expire": 1048576, "minimum-ttl": 2560 }, { "host": "php.net", "class": "IN", "ttl": 300, "type": "AAAA", "ipv6": "2a02:cb41::7" }, { "host": "php.net", "class": "IN", "ttl": 49, "type": "A", "ip": "72.52.91.14" }, { "host": "php.net", "class": "IN", "ttl": 300, "type": "NS", "target": "dns3.easydns.org" }, { "host": "php.net", "class": "IN", "ttl": 300, "type": "NS", "target": "dns4.easydns.info" }, { "host": "php.net", "class": "IN", "ttl": 300, "type": "NS", "target": "dns2.easydns.net" }, { "host": "php.net", "class": "IN", "ttl": 300, "type": "NS", "target": "dns1.easydns.com" } ] }  

Kindly help me.

Best Answer

Add this header before you output your JSON:

header('Content-type: Application/JSON');

If your script returns JSON, you should be using this header anyway. Some applications that expect a JSON response actually require it.

It currently shows up on one line regardless of the JSON_PRETTY_PRINT option because the browser has received a Content-Type:text/html header, so it's rendering that text as an HTML document, in which all your new lines and indentation are reduced to single spaces. If you use the Content-type: Application/JSON header, the browser should show the formatted JSON without needing to use <pre> tags. In fact, if you do use those tags, your script will no longer return valid JSON.

JSON is a data interchange format. It is more human-readable than some other data interchange formats like XML, which is nice, but its main purpose is to pass data between applications. I think the main benefit of JSON_PRETTY_PRINT is for the developer, so they can examine the output more easily while they are working on it. My recommendation is generally to not use it, because if you're not needing to look at the output it just adds unnecessary overhead, and if you are needing to look at the output, you can install a browser extension that formats the JSON even more usefully than JSON_PRETTY_PRINT does.

Related Question