I want to return JSON from a PHP script.
Do I just echo the result? Do I have to set the Content-Type
header?
This is a simple PHP script to return male female and user id as json value will be any random value as you call the script json.php .
Hope this help thanks
<?php
header("Content-type: application/json");
$myObj=new \stdClass();
$myObj->user_id = rand(0, 10);
$myObj->male = rand(0, 5);
$myObj->female = rand(0, 5);
$myJSON = json_encode($myObj);
echo $myJSON;
?>
A simple function to return a JSON response with the HTTP status code.
function json_response($data=null, $httpStatus=200)
{
header_remove();
header("Content-Type: application/json");
http_response_code($httpStatus);
echo json_encode($data);
exit();
}
This question got many answers but none cover the entire process to return clean JSON with everything required to prevent the JSON response to be malformed.
/*
* returnJsonHttpResponse
* @param $success: Boolean
* @param $data: Object or Array
*/
function returnJsonHttpResponse($success, $data)
{
// remove any string that could create an invalid JSON
// such as PHP Notice, Warning, logs...
ob_clean();
// this will clean up any previously added headers, to start clean
header_remove();
// Set the content type to JSON and charset
// (charset can be set to something else)
header("Content-type: application/json; charset=utf-8");
// Set your HTTP response code, 2xx = SUCCESS,
// anything else will be error, refer to HTTP documentation
if ($success) {
http_response_code(200);
} else {
http_response_code(500);
}
// encode your PHP Object or Array into a JSON string.
// stdClass or array
echo json_encode($data);
// making sure nothing is added
exit();
}
References:
response_remove
ob_clean
Content-type JSON
HTTP Codes
http_response_code
json_encode
An easy way to format your domain objects to JSON is to use the Marshal Serializer.
Then pass the data to json_encode
and send the correct Content-Type header for your needs.
If you are using a framework like Symfony, you don't need to take care of setting the headers manually. There you can use the JsonResponse.
For example the correct Content-Type for dealing with Javascript would be application/javascript
.
Or if you need to support some pretty old browsers the safest would be text/javascript
.
For all other purposes like a mobile app use application/json
as the Content-Type.
Here is a small example:
<?php
...
$userCollection = [$user1, $user2, $user3];
$data = Marshal::serializeCollectionCallable(function (User $user) {
return [
'username' => $user->getUsername(),
'email' => $user->getEmail(),
'birthday' => $user->getBirthday()->format('Y-m-d'),
'followers => count($user->getFollowers()),
];
}, $userCollection);
header('Content-Type: application/json');
echo json_encode($data);
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 );
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.