Returning JSON from a PHP Script

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

    As said above:

    header('Content-Type: application/json');
    

    will make the job. but keep in mind that :

    • Ajax will have no problem to read json even if this header is not used, except if your json contains some HTML tags. In this case you need to set the header as application/json.

    • Make sure your file is not encoded in UTF8-BOM. This format add a character in the top of the file, so your header() call will fail.

提交回复
热议问题