Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I want to return JSON from a PHP script.

Do I just echo the result? Do I have to set the Content-Type header?

share|improve this question

10 Answers 10

up vote 760 down vote accepted

While you're usually fine without it, you can and should set the Content-Type header:

<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn't be necessary).

share|improve this answer
6  
just in case: you should use header() commands only in addition with output buffering to avoid "headers already sent" warnings – Kevin Horst Jul 2 '14 at 16:51
1  
It's good practice to always put your header() statements as far to the top of the page as possible so that when you add more code, you aren't tempted to insert code before the header() statement which could break things if you start outputting. – Mikepote Oct 13 '14 at 13:17
3  
The php file have to be encoded in UTF-8 without BOM :) – Krzysztof Kalinowski Nov 20 '14 at 14:57
36  
header('Content-type:application/json;charset=utf-8'); – Timo Huovinen Aug 20 '15 at 12:46
6  
@mikepote I actually don't think it's necessary to have the header command at the top of the PHP file. If you're inadvertently spitting out stuff and that's tripping up your header command, you just need to fix your code because it's broken. – Halfstop Sep 10 '15 at 18:02

A complete piece of nice and clear PHP code returning JSON is:

$option = $_GET['option'];

if ( $option == 1 ) {
    $data = [ 'a', 'b', 'c' ];
    // will encode to JSON array: ["a","b","c"]
    // accessed as example in JavaScript like: result[1] (returns "b")
} else {
    $data = [ 'name' => 'God', 'age' => -1 ];
    // will encode to JSON object: {"name":"God","age":-1}  
    // accessed as example in JavaScript like: result.name or result['name'] (returns "God")
}

header('Content-type: application/json');
echo json_encode( $data );
share|improve this answer
9  
Mental note: starting a reply with "For newbies" is guarantee of few votes. – aesede Sep 30 '14 at 17:55
41  
I laughed at the revision history. – MrHunter Aug 30 '15 at 22:47
5  
I find your affirmation slightly incorrect, if God had 'index' => -1 that would mean he doesn't exist, but having 'age' => -1 just means he existed even before time. Don't try interpreting the Holy Bible on your own dude, ask a priest. – Andrei Cojea Nov 12 '15 at 7:35
6  
@MrHunter , It gets even funnier if you see that the super user Community, which user's id is -1, edited the answer to make it more objective. – Edgar Salazar Feb 25 '16 at 19:55
2  
@philtune OP says "do I just echo the result?" my answer is kind of "yes, you just echo the results, but have in mind this and that", how is that not helpful? My aim was to help people that's just starting using this kind of stuff, like myself the first time I got into this page. – aesede Apr 26 '16 at 13:18

Try json_encode to encode the data and set the content-type with header('Content-type: application/json');.

share|improve this answer

According to the manual on json_encode the method can return a non-string (false):

Returns a JSON encoded string on success or FALSE on failure.

When this happens echo json_encode($data) will output the empty string, which is invalid JSON.

json_encode will for instance fail and return false if its argument contains a non UTF-8 string.

This error condition should be captured in PHP, for example like this:

<?php
header("Content-Type: application/json;charset=utf-8");

// Collect what you need in the $data variable.

$json = json_encode($data);
if ($json === false) {
    // Avoid echo of empty string (which is invalid JSON), and
    // JSONify the error message instead:
    $json = json_encode(array("jsonError", json_last_error_msg()));
    if ($json === false) {
        // This should not happen, but we go all the way now:
        $json = '{"jsonError": "unknown"}';
    }
    // Set HTTP response status code to: 500 - Internal Server Error
    http_response_code(500);
}
echo $json;
?>

Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly.

In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.

Read more about dealing with JSON errors in Documention

share|improve this answer
1  
... and you should set an appropriate HTTP response code (500, probably) when this happens. – zwol Apr 18 '16 at 1:14
    
Thanks, @zwol, for suggesting this! I updated the answer accordingly. – trincot Apr 18 '16 at 8:43
    
upvote for handling the json encode errors – Neo Nov 12 '16 at 8:13

Set the content type with header('Content-type: application/json'); and then echo your data.

share|improve this answer

The answer to your question is here,

It says.

The MIME media type for JSON text is application/json.

so if you set the header to that type, and output your JSON string, it should work.

share|improve this answer

You can use this little PHP library. It sends the headers and give you an object to use it easily.

It looks like :

<?php
// Include the json class
include('includes/json.php');

// Then create the PHP-Json Object to suits your needs

// Set a variable ; var name = {}
$Json = new json('var', 'name'); 
// Fire a callback ; callback({});
$Json = new json('callback', 'name'); 
// Just send a raw JSON ; {}
$Json = new json();

// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';

// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);

// Finally, send the JSON.

$Json->send();
?>
share|improve this answer

Yeah, you'll need to use echo to display output. Mimetype: application/json

share|improve this answer

If you need to get json from php sending custom information you can add this header('Content-Type: application/json'); before to print any other thing, So then you can print you custome echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';

share|improve this answer

As said above:

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

will make the job. but keep in mind that :

  • Ajax will have no problem to read json even if this header is not used, except if your json contains some HTML tags. In this case you need to set the header as application/json.

  • Make sure your file is not encoded in UTF8-BOM. This format add a character in the top of the file, so your header() call will fail.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.