Returning JSON from a PHP Script

前端 未结 18 1474
南方客
南方客 2020-11-21 04:59

I want to return JSON from a PHP script.

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

18条回答
  •  故里飘歌
    2020-11-21 05:38

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

提交回复
热议问题