[英]Why the code is not printing in Pretty Json format?
這是我的代碼:
<?php
$result = dns_get_record("php.net",DNS_ANY);
echo json_encode(array('data' => $result), JSON_PRETTY_PRINT);
?>
我試圖將輸出打印成漂亮的json格式,但不明白為什么它不打印漂亮的json。
這是每次嘗試后得到的輸出:
{ "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" } ] }
請幫助我。
您只需要json_encode()
添加一個參數並添加<pre>
標簽即可。 像這樣:
echo '<pre>';
echo json_encode($data, JSON_PRETTY_PRINT);
echo '</pre>';
在輸出JSON之前添加此標頭:
header('Content-type: Application/JSON');
如果腳本返回JSON,則無論如何都應使用此標頭。 一些期望JSON響應的應用程序實際上需要它。
無論瀏覽器是否使用JSON_PRETTY_PRINT
選項,它當前都顯示在一行上,因為瀏覽器已收到Content-Type:text/html
標頭,因此它將該文本呈現為HTML文檔,其中所有新行和縮進均減少為單個空格。 如果使用Content-type: Application/JSON
標頭,則瀏覽器應顯示格式的JSON,而無需使用<pre>
標記。 實際上,如果您確實使用這些標記,則腳本將不再返回有效的JSON。
JSON是一種數據交換格式。 它比XML之類的其他數據交換格式更易於理解,但是它的主要目的是在應用程序之間傳遞數據。 我認為JSON_PRETTY_PRINT
的主要好處是對開發人員來說,因此他們可以在處理輸出時更輕松地檢查輸出。 我的建議一般是不使用它,因為如果你不需要看它只是增加了不必要的開銷輸出,如果你需要看的輸出,你可以安裝一個瀏覽器擴展,更加格式化JSON比JSON_PRETTY_PRINT
有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.