如何在PHP cURL中设置自定义headers?
大家好!我是PHP新手,正尝试通过cURL向外部API发送POST请求。API文档说需要传递几个自定义headers:`X-API-Key: mysecretkey`、`Content-Type: application/json`和`Authorization: Bearer token123`。我尝试将它们作为字符串传递给`curl_setopt($ch, CURLOPT_HTTPHEADER, ...)`,但不起作用——服务器返回400 Bad Request错误或忽略我的headers。
以下是我当前的代码:
```php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(["name" => "John"]));
curl_setopt($ch, CURLOPT_HTTPHEADER, "X-API-Key: mysecretkey; Content-Type: application/json; Authorization: Bearer token123");
$response = curl_exec($ch);
curl_close($ch);
```
我将所有headers用分号连接成单个字符串传递。也许需要其他方式?另外:如何检查headers是否真的被发送了?