在PHP中使用cURL发送POST请求以运行GraphQL API,你需要遵循以下步骤:
以下是一个使用PHP cURL发送GraphQL POST请求的示例:
<?php
// GraphQL查询或变异
$query = '
mutation {
createUser(name: "John Doe", email: "john.doe@example.com") {
id
name
email
}
}
';
// GraphQL API的URL
$url = 'https://your-graphql-api.com/graphql';
// 初始化cURL会话
$ch = curl_init();
// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['query' => $query]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
// 如果API需要认证,添加相应的头部
// 'Authorization: Bearer YOUR_TOKEN'
]);
// 执行cURL会话并获取响应内容
$response = curl_exec($ch);
// 检查是否有错误发生
if(curl_errno($ch)){
echo 'cURL error: '. curl_error($ch);
}
// 关闭cURL会话
curl_close($ch);
// 解码响应JSON
$result = json_decode($response, true);
// 输出结果
print_r($result);
?>
如果你遇到问题,比如请求失败或者返回错误,你可以:
通过以上步骤,你应该能够在PHP中使用cURL成功发送GraphQL POST请求。如果遇到具体问题,可以根据错误信息进一步排查。
领取专属 10元无门槛券
手把手带您无忧上云