Returning JSON from a PHP Script

I want to return JSON from a PHP script.

Do I just echo the result? Do I have to set the Content-Type header?


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


返回JSON的完整而清晰的PHP代码是:

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

Try json_encode to encode the data and set the content-type with header('Content-type: application/json'); .

链接地址: http://www.djcxy.com/p/45822.html

上一篇: 从PHP返回JSON到JavaScript?

下一篇: 从PHP脚本返回JSON