开发者

Printing JSON formatted like Facebook does

开发者 https://www.devze.com 2023-03-22 16:07 出处:网络
Here the example: https://graph.facebook.com/19292868552 How is it possible? The source of the page is just as the page appears! There\'s no code of any kind. If you try to change the last 2 number i

Here the example: https://graph.facebook.com/19292868552

How is it possible? The source of the page is just as the page appears! There's no code of any kind. If you try to change the last 2 number in the url you can get other examples. How do they print this JSON with carriage return after every element of the array without any sort of <br/>?

In php.net I can't find any way to nicely print JSON like this.

 $vettore = array(
    "uno" => 1,
    "due" => 2,
    "tre" => 3
 );

 header("Content-Type: text/javascript; charset=UTF-8");
 echo json_encode($vettore, JS开发者_开发百科ON_PRETTY_PRINT);


If you look at the reply headers, there's this line:

Content-Type: text/javascript; charset=UTF-8

By this the browser knows that the page is not HTML and doesn't try to format it as such.


Tell the browser that it's plain text, then just pretty print it.

header('Content-type: text/plain');

Although they actually use text/javascript, as shown by the page properties.


You could do it like this, it doesn't seem the best way to achieve neatly formatted Json but it does work.

$json_stuff = array(
   "url"         => "http://example.com",
   "name"        => "my name",
   "description" => "some description",
   "other"       => "some text"
);

foreach ($json_stuff as $key => $val) {
   $json_string .= "\"${key}\" : \"${val}\",\n";
}

header('Content-Type: application/json');
die("{\n".rtrim($json_string, ",\n")."\n}");

Above would output below with line breaks and without backslashs in urls.

{
"url" : "http://example.com",
"name" : "my name",
"description" : "some description",
"other" : "some text"
}
0

精彩评论

暂无评论...
验证码 换一张
取 消