如何使用PHP发送POST请求:curl、file_get_contents及其他方法
大家好!我是PHP新手,正在尝试弄清楚如何向外部服务器发送POST请求。我需要将表单数据(姓名、邮箱)发送到API端点并获取响应。我试过使用file_get_contents(),但没成功——要么是我错误地构建了上下文,要么是根本用错了方法。
这是我的代码:
```php
$url = 'https://example.com/api/users';
$data = ['name' => 'Иван', 'email' => 'ivan@example.com'];
$result = file_get_contents($url, false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode($data)
]
]));
if ($result === false) {
echo '发送错误';
} else {
echo $result;
}
```
问题是我得到false或空响应。也许我设置header的方式不对?或者有更简单的方法?我听说过cURL,但它看起来复杂。请告诉我如何正确发送POST请求。