PHP“漂亮的打印”json_encode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7097374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:00:09  来源:igfitidea点击:

PHP "pretty print" json_encode

phpjsonencode

提问by Brian

Possible Duplicate:
Pretty-Printing JSON with PHP

可能的重复:
使用 PHP 漂亮地打印 JSON

I'm working on a script that creates a JSON file. Right now I'm just using json_encode(PHP 5.2.x) to encode an array into JSON output. Then I print the returned value to a file and save it. Problem is that the client wants to be able to open these JSON files for readability, so I'd like to add line breaks in and "pretty print" the JSON output. Any ideas on how to do this? My only other alternative that I can see is to not use json_encodeat all and just write the file contents manually and add in my own line breaks for each line.

我正在编写一个创建 JSON 文件的脚本。现在我只是使用json_encode(PHP 5.2.x) 将数组编码为 JSON 输出。然后我将返回的值打印到文件并保存。问题是客户端希望能够打开这些 JSON 文件以提高可读性,因此我想在其中添加换行符并“漂亮地打印”JSON 输出。关于如何做到这一点的任何想法?我能看到的唯一其他选择是根本不使用json_encode,只需手动编写文件内容并为每一行添加我自己的换行符。

Here's what I get:

这是我得到的:

{"product_name":"prod1","val1":1,"val2":8}

Here's what I want:

这是我想要的:

{
  "product_name":"prod1",
  "val1":1,
  "val2":8
}

I suppose I could also just replace every comma with a command followed by a \n, and same for the brackets... Thoughts?

我想我也可以用一个命令替换每个逗号,后跟一个 \n,括号也一样......想法?

回答by petrkotek

PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).

PHP 自 5.4.0(发布日期 01-Mar-2012)起就有 JSON_PRETTY_PRINT 选项。

This should do the job:

这应该可以完成这项工作:

$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);

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

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

Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)

注意:如果您在 HTML 中打印它以保留格式,请不要忘记在“<pre>”之前和“</pre>”之后回显;)

回答by sg3s

Hmmm $array = json_decode($json, true);will make your string an array which is easy to print nicely with print_r($array, true);

$array = json_decode($json, true);将使您的字符串成为一个易于打印的数组print_r($array, true);

But if you really want to prettify your json... Check this out

但是如果你真的想美化你的 json ......看看这个

回答by Cam Tullos

Here's a function to pretty up your json: pretty_json

这是一个用来修饰你的 json 的函数: pretty_json

回答by bohwaz

And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:

而对于 PHP 5.3,你可以使用这个函数,它可以嵌入到一个类中或以程序风格使用:

http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php

http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php