Returning JSON from a PHP Script Returning JSON from a PHP Script php php

Returning JSON from a PHP Script


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; charset=utf-8');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).


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 );


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:

<?phpheader("Content-Type: application/json");// 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(["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 PHP's Documentation.