1

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?

zeddex
  • 1,260
  • 5
  • 21
  • 38

1 Answers1

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:

echo json_encode($results, JSON_PRETTY_PRINT);
deChristo
  • 1,860
  • 2
  • 17
  • 29
  • 1
    Thanks that did the trick, also do you know if there is any way to keep a regular URL rather than escaped? – zeddex Nov 24 '16 at 19:04
  • Just found it no worries, if anyone else needs it: echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); – zeddex Nov 24 '16 at 19:05
  • Take a look at: http://stackoverflow.com/questions/3723243/why-does-json-encoder-adds-escaping-character-when-encoding-urls – deChristo Nov 24 '16 at 19:07