Return JSON from PHP script
P粉752812853
P粉752812853 2023-10-09 10:46:10
0
2
555

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粉752812853
P粉752812853

reply all(2)
P粉539055526

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粉311563823

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!