I want to return JSON from a PHP script.
Do I just echo the result? Do I have to set the Content-Type
header?
You can simply use the json_encode() function to return JSON response from a PHP script. Also, if you're passing JSON data to a JavaScript program, make sure set the Content-Type header.
To get JSON with Curl, you need to make an HTTP GET request and provide the Accept: application/json request header. The application/json request header is passed to the server with the curl -H command-line option and tells the server that the client is expecting JSON in response.
❮ Previous Next ❯ A common use of JSON is to read data from a web server, and display the data in a web page. This chapter will teach you how to exchange JSON data between the client and a PHP server.
The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With