Returning JSON from a PHP Script

前端 未结 18 1404
南方客
南方客 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:37

    An easy way to format your domain objects to JSON is to use the Marshal Serializer. Then pass the data to json_encode and send the correct Content-Type header for your needs. If you are using a framework like Symfony, you don't need to take care of setting the headers manually. There you can use the JsonResponse.

    For example the correct Content-Type for dealing with Javascript would be application/javascript.

    Or if you need to support some pretty old browsers the safest would be text/javascript.

    For all other purposes like a mobile app use application/json as the Content-Type.

    Here is a small example:

     $user->getUsername(),
            'email'    => $user->getEmail(),
            'birthday' => $user->getBirthday()->format('Y-m-d'),
            'followers => count($user->getFollowers()),
        ];
    }, $userCollection);
    
    header('Content-Type: application/json');
    echo json_encode($data);
    

提交回复
热议问题