php post方式发送json
时间: 2023-08-07 21:07:03 浏览: 64
可以使用以下代码示例将 JSON 数据以 POST 方式发送到服务器:
```php
<?php
// JSON 数据
$data = array('name' => 'John', 'age' => 30);
$json = json_encode($data);
// 设置 POST 请求头
$header = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
);
// 初始化 CURL 对象
$ch = curl_init();
// 设置 CURL 配置
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 执行 CURL 请求并获取响应
$response = curl_exec($ch);
// 关闭 CURL 对象
curl_close($ch);
// 处理响应数据
if ($response === false) {
// 请求失败
echo '请求失败';
} else {
// 请求成功
$result = json_decode($response, true);
print_r($result);
}
?>
```
在上面的示例中,我们首先将要发送的 JSON 数据编码为字符串,然后设置 POST 请求头,初始化 CURL 对象,设置 CURL 配置,执行 CURL 请求并获取响应,最后处理响应数据。需要注意的是,在设置 CURLOPT_POSTFIELDS 选项时,需要传入编码后的 JSON 字符串。