I want to return JSON from a PHP script.
Do I just echo the results? Do I have to set the Content-Type
header?
P粉5390555262023-10-10 09:38:23
The complete and clear PHP code that returns 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 );
P粉3115638232023-10-10 00:45:19
While it's 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 specific framework, I usually allow some request parameters to modify the output behavior. Often for quick troubleshooting it can be useful to not send the header, or sometimes print_r
the data payload to observe it (although in most cases this is not necessary).