I am trying to make a simple JSON API for a website similar to this:
我正在尝试为类似这样的网站制作一个简单的JSON API:
https://api.coinmarketcap.com/v1/ticker/bitcoin
My current code:
我目前的代码:
<?php
// Creating the data array
$data = array(
'id' => '1',
'url' => 'http://twitter.com',
'text' => 'test 001',
);
// Formats output in nice JSON for you
function return_json($array, $name = 'data') {
$new_array = array($name => $array);
$return = json_encode($new_array, JSON_PRETTY_PRINT);
return $return;
}
echo return_json($data);
?>
The problem is that the current output is nothing like from that websites API where it is nicely formatted and it is a single line like:
问题是,当前的输出与网站API完全不同,它的格式很好,而且它是一行,如:
{ "data": { "id": "1", "url": "http:\/\/twitter.com", "text": "test 001" } }
How can i generate and output JSON nicely formatted and readable when someone visits the page?
当有人访问页面时,如何生成和输出格式良好且可读的JSON?
1 个解决方案
#1
1
First set the header for the response:
首先设置响应的标头:
header('Content-Type: application/json');
And add the JSON_PRETTY_PRINT
parameter to json_encode()
like this:
并将JSON_PRETTY_PRINT参数添加到json_encode(),如下所示:
echo json_encode($results, JSON_PRETTY_PRINT);
#1
1
First set the header for the response:
首先设置响应的标头:
header('Content-Type: application/json');
And add the JSON_PRETTY_PRINT
parameter to json_encode()
like this:
并将JSON_PRETTY_PRINT参数添加到json_encode(),如下所示:
echo json_encode($results, JSON_PRETTY_PRINT);