如何用纯PHP发起GraphQL查询?附代码求助
纯PHP发起GraphQL查询的实现方案
问题描述
我需要使用纯PHP发起GraphQL查询,请问这是否可行?该如何实现?
GraphQL请求:
{ getLastLowestProductPrices( lastLowestPricesInput: [{date: "2023-01-01", productId: 14397, sizeId: "uniw"}] ) { id sizes { id price { gross { value currency } } } }端点:
https://trening-dev1.iai-shop.com/graphql/v1/?docLang=pl我编写的PHP代码如下:
function do_post_request($url, $data) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data) ) ); return curl_exec($ch); } function get($endpoint) { $json = '{ getLastLowestProductPrices( lastLowestPricesInput: [{date: "2023-01-01", productId: 14397, sizeId: "uniw"}] ) { id sizes { id price { gross { value currency } } } }'; $result = do_post_request($endpoint, $json); print_r($result); } $endpoint = 'https://trening-dev1.iai-shop.com/graphql/v1/?docLang=pl'; get($endpoint);
可行,修正代码即可正常运行
GraphQL的POST请求要求请求体是包含query字段的JSON对象,你直接发送查询语句的写法不符合标准格式,另外缺少错误排查逻辑,以下是修正后的代码:
function do_post_request($url, $query) { // 构建GraphQL标准请求体 $postData = json_encode([ 'query' => $query ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', ]); // 添加超时设置避免无限等待 curl_setopt($ch, CURLOPT_TIMEOUT, 10); $response = curl_exec($ch); // 检查curl请求错误 if(curl_errno($ch)){ echo '请求错误: ' . curl_error($ch); $response = false; } curl_close($ch); return $response; } function getProductPrices($endpoint) { $graphqlQuery = '{ getLastLowestProductPrices( lastLowestPricesInput: [{date: "2023-01-01", productId: 14397, sizeId: "uniw"}] ) { id sizes { id price { gross { value currency } } } } }'; $result = do_post_request($endpoint, $graphqlQuery); if($result){ // 解析响应为数组方便处理 $data = json_decode($result, true); print_r($data); } } $endpoint = 'https://trening-dev1.iai-shop.com/graphql/v1/?docLang=pl'; getProductPrices($endpoint);
关键修正说明
- 把GraphQL查询语句包裹在
query字段中,再编码为JSON发送,这是GraphQL服务接受的标准格式 - 替换
CURLOPT_CUSTOMREQUEST为CURLOPT_POST,符合POST请求的常规用法 - 移除手动计算的
Content-Length,curl会自动处理该字段,避免编码错误导致长度不符 - 添加curl错误检查,方便排查请求失败原因
- 对响应做JSON解析,便于后续业务逻辑处理
内容的提问来源于stack exchange,提问作者pasza
相关产品推荐
相关产品推荐

