首页  >  文章  >  后端开发  >  如何在 PHP 中处理 JSON 请求?

如何在 PHP 中处理 JSON 请求?

Patricia Arquette
Patricia Arquette原创
2024-10-20 23:01:29270浏览

How to Handle JSON Requests in PHP?

在 PHP 中处理 JSON 请求

在 AJAX 请求中提交数据时,contentType 标头指定要发送的数据的格式。默认的 x-www-form-urlencoded 编码将数据编码为键值对,而 application/json 将其编码为 JSON 字符串。

当 contentType 设置为 application/json 时,PHP 内置的 $_POST保存表单参数的变量变为空。这是因为原始 JSON 字符串不会自动解析为单独的参数。

要在 PHP 中正确处理 JSON 请求,请使用以下代码:

<code class="php"><?php
var_dump(json_decode(file_get_contents('php://input')));
?></code>

file_get_contents('php:// input') 读取原始请求正文。然后 json_decode() 将 JSON 字符串解析为 PHP 对象或数组,可以像任何其他 PHP 变量一样访问它。

这是一个示例用法:

<code class="php">// Assume an incoming request with the following JSON body:
{
  "my_params": 123
}

// Parse the JSON request
$data = json_decode(file_get_contents('php://input'));

// Access the parsed data like any other PHP variable
$my_params = $data->my_params;</code>

以上是如何在 PHP 中处理 JSON 请求?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn