从PHP脚本返回JSON [英] Returning JSON from a PHP Script
本文介绍了从PHP脚本返回JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从PHP脚本中返回JSON。
I want to return JSON from a PHP script.
我只是回应结果吗?是否必须设置 Content-Type
标题?
Do I just echo the result? Do I have to set the Content-Type
header?
推荐答案
while如果没有它,你可以也应该设置Content-Type标题:
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);
如果我没有使用特定的框架,我通常允许一些请求参数修改输出行为。它通常可以用于快速排除故障,不发送头文件,或者有时候print_r数据有效载荷(但在大多数情况下,它不应该是必须的)。
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).
这篇关于从PHP脚本返回JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文