Format echo json_encode
Format echo json_encode
这个问题已经有了答案:
我想要格式化 echo json_encode 的输出,目前的输出是
{"results":{"course":"CC140","books":{"book":[[{"id":"300862","title":"Building object-oriented software","isbn":"0070431965","borrowedcount":"6"}]]}}}
然而,我想要的输出应该是这样的:
{ "results": { "course": "CC140", "books": { "book": [ [ { "id": "300862", "title": "Building object-oriented software", "isbn": "0070431965", "borrowedcount": "6" } ] ] } } }
这里是生成JSON的代码
$temp = array(); foreach ($my_array as $counter => $bc) { $temp['id'] = "$id[$counter]"; $temp['title'] = "$title[$counter]"; $temp['isbn'] = "$isbn[$counter]"; $temp['borrowedcount'] = "$borrowedcount[$counter]"; $t2[] = $temp; } $data = array( "results" => array( "course" => "$cc", "books" => array( "book" => array( $t2 ) ) ) ); echo json_encode($data);
任何帮助或指点将不胜感激,谢谢
添加这个
header('Content-type: application/json'); echo json_encode($data, JSON_PRETTY_PRINT);
可以格式化JSON,但标题也输出了整个HTML文档
admin 更改状态以发布 2023年5月21日
我要给的第一个建议是:不要这么做。JSON是一种数据格式。使用工具处理它,而不是试图让你的服务器格式化它。
如果你要忽略这个建议,那么请查看json_encode
函数的手册,其中列出了一些选项,包括JSON_PRETTY_PRINT
,它被描述为:在返回数据中使用空格来格式化数据。从PHP 5.4.0版本开始提供。
因此,步骤如下:
- 确保你正在使用PHP 5.4.0或更新版本
json_encode($data, JSON_PRETTY_PRINT);