php发送json示例
时间: 2023-04-10 11:00:46 浏览: 101
以下是一个 PHP 发送 JSON 的示例:
```php
$data = array(
'name' => 'John Doe',
'email' => 'johndoe@example.com',
'phone' => '123-456-7890'
);
$json = json_encode($data);
$url = 'https://example.com/api';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
```
这个示例中,我们首先创建了一个包含一些数据的数组,然后使用 `json_encode()` 函数将其转换为 JSON 格式。接下来,我们设置了一个 URL,然后使用 cURL 发送 POST 请求,将 JSON 数据作为请求体发送。我们还设置了一个 `Content-Type` 头部,告诉服务器我们发送的是 JSON 数据。最后,我们使用 `curl_exec()` 函数执行请求,并输出服务器的响应。