php将post接收到的json转为数组
在PHP中,你可以使用 file_get_contents
函数来获取POST请求中的原始JSON数据,然后使用 json_decode
函数将其转换为数组。以下是一个示例代码:
<?php
// 获取POST请求中的原始JSON数据
$json = file_get_contents('php://input');
// 将JSON数据转换为PHP数组
$data = json_decode($json, true);
// ���查json_decode是否成功
if (json_last_error() === JSON_ERROR_NONE) {
// 成功转换为数组
print_r($data);
} else {
// 处理JSON解析错误
echo "JSON解析错误: " . json_last_error_msg();
}
?>
在这个示例中:
file_get_contents('php://input')
用于读取POST请求的原始数据。json_decode($json, true)
将JSON字符串转换为PHP数组。第二个参数为 true
,表示将JSON对象转换为关联数组。json_last_error()
和 json_last_error_msg()
用于检查和处理JSON解析错误。你可以将这个代码放在一个PHP文件中,然后通过POST请求发送JSON数据到这个文件