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?

1

1 Answer 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:

echo json_encode($results, JSON_PRETTY_PRINT);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that did the trick, also do you know if there is any way to keep a regular URL rather than escaped?
Just found it no worries, if anyone else needs it: echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.