程序go 2011-05-19 05:08 采纳率: 100%
浏览 548
已采纳

使用 PHP 美化打印 JSON

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.

转载于:https://stackoverflow.com/questions/6054033/pretty-printing-json-with-php

  • 写回答

22条回答 默认 最新

  • 喵-见缝插针 2012-02-02 22:20
    关注

    PHP 5.4 offers the JSON_PRETTY_PRINT option for use with the json_encode() call.

    http://php.net/manual/en/function.json-encode.php

    <?php
    ...
    $json_string = json_encode($data, JSON_PRETTY_PRINT);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(21条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退