从 PHP 脚本返回 JSON [英] Returning JSON from a PHP Script

查看:21
本文介绍了从 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?

推荐答案

虽然通常没有它你也可以,但你可以并且应该设置 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; charset=utf-8');
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆