使用 PHP 打印漂亮的 JSON [英] Pretty-Printing JSON with PHP
问题描述
我正在构建一个 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_encode()
调用的 JSON_PRETTY_PRINT
选项.
PHP 5.4 offers the JSON_PRETTY_PRINT
option for use with the json_encode()
call.
http://php.net/manual/en/function.json-编码.php
<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);
这篇关于使用 PHP 打印漂亮的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!