在 PHP 中,可以使用 json_encode()
函数将 PHP 数组或对象转换为 JSON 数据,并使用 header()
函数设置响应头为 JSON 数据类型。
以下是一个示例代码:
'John', 'age' => 25, 'email' => 'john@example.com' ]; // 将关联数组转换为 JSON 数据格式 $jsonData = https://www.yisu.com/ask/json_encode($data);'Content-Type: application/json'); // 输出 JSON 数据给客户端 echo $jsonData; ?>
以上代码会将 $data
数组转换为如下的 JSON 数据格式,并返回给客户端:
{ "name": "John", "age": 25, "email": "john@example.com" }
注意:在调用 header()
函数之前不能有任何输出,包括空格、换行等。