zeddex zeddex - 7 days ago 5
JSON Question

PHP - Making a simple JSON API With Formatting

I am trying to make a simple JSON API for a website similar to this:

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:

{ "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?

Answer

First set the header for the response:

header('Content-Type: application/json');

And add the JSON_PRETTY_PRINT parameter to json_encode() like this:

echo json_encode($results, JSON_PRETTY_PRINT);
Comments