如何使用PHP接收POST的JSON数据
封面图
•
2025-10-26
•
PHP
189
0
0
0
在 PHP 中接收 **POST 请求中的 JSON 数据**,可以通过以下步骤实现: --- ### ✅ 步骤 1:获取原始 POST 数据 PHP 默认不会自动将 POST 的 JSON 数据解析为数组或对象。你需要手动获取原始数据。 ```php $data = file_get_contents("php://input"); ``` --- ### ✅ 步骤 2:将 JSON 字符串解码为 PHP 数组或对象 使用 `json_decode()` 函数进行解码: ```php $decodedData = json_decode($data, true); // true 表示返回数组,不加则返回对象 ``` --- ### ✅ 完整示例代码: ```php <?php // 获取原始 POST 数据 $data = file_get_contents("php://input"); // 将 JSON 解码为数组 $decodedData = json_decode($data, true); // 检查是否有错误 if (json_last_error() === JSON_ERROR_NONE) { // 处理数据 if (isset($decodedData['username'])) { echo "接收到用户名: " . $decodedData['username']; } else { echo "未找到 username 字段"; } } else { echo "JSON 解析失败: " . json_last_error_msg(); } ?> ``` --- ### 📌 注意事项: - 如果你使用的是 `$_POST` 而不是 `file_get_contents("php://input")`,那只能接收表单提交的数据(如 `application/x-www-form-urlencoded`),不能直接接收 JSON。 - 如果你使用的是 `$_SERVER['CONTENT_TYPE']`,可以判断请求类型是否为 `application/json`: ```php if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['CONTENT_TYPE'] === 'application/json') { // 处理 JSON 数据 } ``` --- ### ✅ 示例请求(使用 curl 或 Postman): ```bash curl -X POST http://example.com/your_script.php \ -H "Content-Type: application/json" \ -d '{"username": "john", "age": 30}' ``` --- 如果你还有其他问题,比如如何处理文件上传、验证 JSON 格式等,也可以继续问我!
上一篇:
PHP - Iterator接口介绍
下一篇:
VsCode 配置PHP Debug 调试代码
标题录入,一次不能超过6条
返回顶部
留言
留言
评论