用PHP漂亮打印JSON [英] Pretty-Printing JSON with PHP

查看:89
本文介绍了用PHP漂亮打印JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个PHP脚本,该脚本将JSON数据提供给另一个脚本.我的脚本将数据构建到大型关联数组中,然后使用json_encode输出数据.这是一个示例脚本:

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"
}

有没有一种方法可以在PHP中做到这一点而又不会造成丑陋的入侵?似乎是 Facebook 上的某人知道的.

Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.

推荐答案

PHP 5.4提供了JSON_PRETTY_PRINT选项,可用于json_encode()调用.

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);

这篇关于用PHP漂亮打印JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆