PHP“漂亮打印" json_encode [英] PHP "pretty print" json_encode

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

问题描述

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

Possible Duplicate:
Pretty-Printing JSON with PHP

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

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_encode at all and just write the file contents manually and add in my own line breaks for each line.

这就是我得到的:

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

这就是我想要的:

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

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

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

推荐答案

PHP自5.4.0(发布日期为2012年3月1日)以来具有JSON_PRETTY_PRINT选项.

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

这应该可以完成工作:

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

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

注意:如果您使用HTML格式打印以保留格式,请不要忘记在其前回显< pre>"和在其后显出</pre>;)

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

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

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