"Jhon Andrew", "recipient" => "Someone OverThe I-6ren">
gpt4 book ai didi

json - 如何从 PHP 文件输出格式正确的 JSON?

转载 作者:行者123 更新时间:2023-12-03 23:53:09 25 4
gpt4 key购买 nike

我有这个代码:

<?php

header('Content-Type: text/javascript; charset=UTF-8');
header('Cache-Control: private, no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: Sat, 01 Jan 2000 00:00:00 GMT');

$data = array(
"data" => array(
"sender" => "Jhon Andrew",
"recipient" => "Someone OverThe Internet",
"conversation" =>
array(
"unix" => "1234567890",
"message" => "Lorem ipsum dolor sit amet."
),
array(
"unix" => "0987654321",
"message" => "Tema tis rolod muspi merol."
)
)
);

echo json_encode($data);

?>

我期待这样的结果:

{
"data": {
"sender":"Jhon Andrew",
"recipient":"Someone OverThe Internet",
"message":"Lorem ipsum dolor sit amet."
}
}

但我只在一行中显示了它,如下所示:

{"data":{"sender":"Jhon Andrew","recipient":"Someone OverThe Internet","message":"Lorem ipsum dolor sit amet."}}

如何才能像我期望的那样获得格式正确的 JSON 输出?这实际上并不重要,但我只是想以良好的格式查看结果。


...by the way, I just copied the headers from facebooks graph link because that is how I want to output the result. Example: graph.facebook.com/mOngsAng.gA


It is valid of course. All I want to know is how to output it like this: graph.facebook.com/mOngsAng.gA - As you can see it is properly formatted. I mean it has line breaks and indentions. Unlike what I am getting is just showed in one line.

最佳答案

看看 json_encode()JSON_PRETTY_PRINT 标志在 php 手册中。您可以简单地使用:

$data = json_encode($data, JSON_PRETTY_PRINT);

如果您使用的不是 PHP 5.4 或更高版本,请尝试接受问题的答案:Pretty-Printing JSON with PHP .

但是,您的是有效 json 输出!

关于json - 如何从 PHP 文件输出格式正确的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13620509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com