从 PHP 脚本返回 JSON
我想从PHP脚本返回JSON。
我只是回声结果吗?我必须设置标头吗?Content-Type
虽然没有它通常很好,但你可以并且应该设置标题:Content-Type
<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
如果我不使用特定的框架,我通常允许一些请求参数修改输出行为。它通常可用于快速故障排除,不发送标头,或者有时数据有效负载来吸引它(尽管在大多数情况下,它不应该是必需的)。print_r
返回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 );