使用 PHP 漂亮地打印 JSON
我正在构建一个 PHP 脚本,将 JSON 数据提供给另一个脚本。我的脚本将数据构建到一个大型关联数组中,然后使用 json_encode 输出数据。这是一个示例脚本:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
上面的代码产生以下输出:
{"a":"apple","b":"banana","c":"catnip"}
如果您有少量数据,这很好,但我更喜欢这样的东西:
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
有没有办法在 PHP 中做到这一点,而不需要丑陋的黑客?似乎 Facebook 的某人已经弄清楚了。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(27)
PHP 5.4 提供了用于
json_encode()
调用的JSON_PRETTY_PRINT
选项。https://php.net/manual/en/function.json-encode.php
PHP 5.4 offers the
JSON_PRETTY_PRINT
option for use with thejson_encode()
call.https://php.net/manual/en/function.json-encode.php
该函数将采用 JSON 字符串并将其缩进,使其非常可读。它也应该是收敛的,
输入
输出
代码
This function will take JSON string and indent it very readable. It also should be convergent,
Input
Output
Code
很多用户建议你使用
哪一个是绝对正确的。但这还不够,浏览器需要了解数据的类型,您可以在将数据回显给用户之前指定标头。
这将产生格式良好的输出。
或者,如果您喜欢扩展,可以使用 Chrome 的 JSONView。
Many users suggested that you use
Which is absolutely right. But it's not enough, the browser needs to understand the type of data, you can specify the header just before echo-ing the data back to the user.
This will result in a well formatted output.
Or, if you like extensions you can use JSONView for Chrome.
我意识到这个问题是问如何将关联数组编码为格式漂亮的 JSON 字符串,因此这并不能直接回答问题,但如果您有一个已经是 JSON 格式的字符串,则可以使其变得非常简单通过解码和重新编码(需要 PHP >= 5.4):
示例:
输出:
I realize this question is asking about how to encode an associative array to a pretty-formatted JSON string, so this doesn't directly answer the question, but if you have a string that is already in JSON format, you can make it pretty simply by decoding and re-encoding it (requires PHP >= 5.4):
Example:
This outputs:
将多个答案粘合在一起符合我对现有 json: 的需求
Gluing several answers together fit my need for existing json:
我有同样的问题。
无论如何,我只是在这里使用了 json 格式化代码:
http: //recursive-design.com/blog/2008/03/11/format-json-with-php/
非常适合我的需要。
还有一个更维护的版本: https://github.com/GerHobbelt/nicejson-php
I had the same issue.
Anyway I just used the json formatting code here:
http://recursive-design.com/blog/2008/03/11/format-json-with-php/
Works well for what I needed it for.
And a more maintained version: https://github.com/GerHobbelt/nicejson-php
我已经使用过这个:
或者使用 php 标头,如下所示:
I have used this:
Or use php headers as below:
更容易提醒:输入 128
128 是常量“JSON_PRETTY_PRINT”的同义词
( PHP 文档站点)
much easier to remind: enter 128
128 is a synonyme for the constant "JSON_PRETTY_PRINT"
( PHP Docs Site)
我从 Composer 获取了代码:https://github。 com/composer/composer/blob/master/src/Composer/Json/JsonFile.php和nicejson:https://github.com/GerHobbelt/nicejson-php/blob/master/nicejson.php
Composer 代码很好,因为它从 5.3 流畅地更新到 5.4,但它只编码对象,而 Nicejson 接受 json 字符串,所以我合并了它们。该代码可用于格式化 json 字符串和/或编码对象,我目前在 Drupal 模块中使用它。
I took the code from Composer : https://github.com/composer/composer/blob/master/src/Composer/Json/JsonFile.php and nicejson : https://github.com/GerHobbelt/nicejson-php/blob/master/nicejson.php
Composer code is good because it updates fluently from 5.3 to 5.4 but it only encodes object whereas nicejson takes json strings, so i merged them. The code can be used to format json string and/or encode objects, i'm currently using it in a Drupal module.
格式化 JSON 数据的最佳方式就是这样!
将 $response 替换为您需要转换为 JSON 的数据
best way to format JSON data is like this!
Replace $response with your Data which is required to be converted to JSON
有彩色全输出:Tiny Solution
代码:
Have color full output: Tiny Solution
Code:
如果您使用的是 Firefox,请安装 JSONovich。我知道这并不是一个真正的 PHP 解决方案,但它确实可以用于开发/调试。
If you are on firefox install JSONovich. Not really a PHP solution I know, but it does the trick for development purposes/debugging.
php>5.4 的简单方法:就像 Facebook 图表中
浏览器中的结果 一样
Simple way for php>5.4: like in Facebook graph
Result in browser
将
Use
<pre>
in combination withjson_encode()
and theJSON_PRETTY_PRINT
option:如果您有现有的 JSON (
$ugly_json
)If you have existing JSON (
$ugly_json
)您可以在 switch 语句中稍微修改 Kendall Hopkins 的答案,通过将 json 字符串传递到以下内容来获得外观非常干净且缩进良好的打印
输出
:内联在您的 php 中并享受打印输出。如果您是极简主义者并且出于某种原因不喜欢括号,则可以通过将
$char.="
替换为";
$char 来轻松摆脱这些括号="
在 $char 上的前三个开关案例中。以下是对卡尔加里市的 google 地图 API 调用所得到的结果";
You can modify Kendall Hopkins' answer a little in the switch statement to get a pretty clean looking and nicely indented printout by passing a json string into the following:
}
Now just run the function prettyPrint( $your_json_string ); inline in your php and enjoy the printout. If you're a minimalist and don't like brackets for some reason, you can get rid of those easily by replacing the
$char.="<br>";
with$char="<br>";
in the top three switch cases on $char. Here's what you get for a google maps API call for the city of Calgary对于运行 PHP 5.3 或之前版本的用户,您可以尝试以下操作:
For those running PHP version 5.3 or before, you may try below:
我通常使用其中之一。
如果您已有 JSON 字符串,则只需使用
echo()
和print_r()
的组合即可。不要忘记将
print_r()
的第二个参数传递给true
,以便它返回值而不是打印它:或者您可以使用
die()
方便调试:如果你有一个数组,你需要先将其转换为 JSON 字符串。
请务必使用
JSON_PRETTY_PRINT
标志设置json_encode()
的第二个参数,以便正确呈现 JSON:或进行调试:
I usually use one of these one-liners.
If you already have an JSON string, you can simply use a combination of
echo()
andprint_r()
.Don't forget to pass the second parameter of
print_r()
totrue
so that it returns the value rather than printing it:or you can use
die()
which is handy for debugging:If you have an array, you need to convert it to a JSON string before.
Be sure to set the second parameter of
json_encode()
with theJSON_PRETTY_PRINT
flag so your JSON will be correctly rendered:or for debugging:
这个解决方案使 JSON 变得“非常漂亮”。不完全是 OP 所要求的,但它可以让您更好地可视化 JSON。
}
This solution makes 'really pretty' JSON. Not exactly what the OP was asking for, but it lets you visualise the JSON better.
}
如果您仅使用
$json_string = json_encode($data, JSON_PRETTY_PRINT);
,您将在浏览器中看到类似这样的内容(使用 Facebook 链接 来自问题:) ):但是如果您使用了像 JSONView(即使没有上面的 PHP 选项),那么您将获得一个更更易读的可调试解决方案< /strong> 您甚至可以轻松折叠/折叠每个 JSON 对象,如下所示:
If you used only
$json_string = json_encode($data, JSON_PRETTY_PRINT);
, you will get in the browser something like this (using the Facebook link from the question :) ):but if you used a chrome Extension like JSONView (even without the PHP option above), then you get a more pretty readable debuggable solution where you can even Fold/Collapse each single JSON object easily like this:
你可以像下面这样做。
上面的输出有点像 Facebook。
You could do it like below.
Above would output kind of like Facebook.
递归解决方案的经典案例。这是我的:
用法:
干杯
Classic case for a recursive solution. Here's mine:
Usage:
Cheers
以下是对我有用的内容:
test.php 的内容:
输出:
另请注意 html 中“pre”标签的使用。
希望对某人有帮助
The following is what worked for me:
Contents of test.php:
output:
Also note the use of "pre" tag in html.
Hope that helps someone
print_r PHP 的漂亮打印
PHP 示例
print_r pretty print for PHP
Example PHP
1 -
json_encode($rows,JSON_PRETTY_PRINT);
返回带有换行符的美化数据。这对于命令行输入很有帮助,但正如您所发现的,它在浏览器中看起来并不那么漂亮。浏览器将接受换行符作为源(因此,查看页面源确实会显示漂亮的 JSON),但它们不用于格式化浏览器中的输出。浏览器需要 HTML。2 - 使用此功能 github
1 -
json_encode($rows,JSON_PRETTY_PRINT);
returns prettified data with newline characters. This is helpful for command line input, but as you've discovered doesn't look as pretty within the browser. The browser will accept the newlines as the source (and thus, viewing the page source will indeed show the pretty JSON), but they aren't used to format the output in browsers. Browsers require HTML.2 - use this fuction github
这是我自己使用的函数,API 就像 json_encode 一样,除了它有第三个参数
exclude_flags
以防你想排除一些默认标志(如 JSON_UNESCAPED_SLASHES)here's the function i use myself, the api is just like json_encode, except it has a 3rd argument
exclude_flags
in case you want to exclude some of the default flags (like JSON_UNESCAPED_SLASHES)如果您正在使用MVC,
请尝试在控制器中执行此操作
,然后如果您调用 /getLatestUsers,您将获得漂亮的 JSON 输出;)
If you are working with MVC
try doing this in your controller
then if you call /getLatestUsers you will get a pretty JSON output ;)