How to output a properly formatted JSON from a PHP file?
I have this code:
<?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);
?>
And I was expecting this kind of result:
{
"data": {
"sender":"Jhon Andrew",
"recipient":"Someone OverThe Internet",
"message":"Lorem ipsum dolor sit amet."
}
}
But I got it displayed in just one line, like this:
{"data":{"sender":"Jhon Andrew","recipient":"Someone OverThe Internet","message":"Lorem ipsum dolor sit amet."}}
How can I get properly formatted JSON output just like what I am expecting? It's not really important actually, but I just want to see the result in good format.
...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.
Take a look at JSON_PRETTY_PRINT
flag of json_encode()
in php manual. You can simply use:
$data = json_encode($data, JSON_PRETTY_PRINT);
If you aren't using PHP 5.4
or greater try with the accepted answer of the question: Pretty-Printing JSON with PHP.
However, yours is a valid json output!
链接地址: http://www.djcxy.com/p/47282.html上一篇: 如何传递函数中的常量以供PHP中的另一个函数使用?
下一篇: 如何从PHP文件输出格式正确的JSON?