喵-见缝插针 2010-10-31 10:23 采纳率: 0%
浏览 253
已采纳

从 PHP 脚本返回 JSON

I want to return JSON from a PHP script.

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

转载于:https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script

  • 写回答

15条回答 默认 最新

  • 7*4 2010-10-31 10:27
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部