PHP调用GraphQL接口出现语法错误,请求协助排查
解决GraphQL查询语法错误问题
问题根源
你的核心问题是GraphQL查询语法不符合规范,同时PHP字符串处理和请求结构也存在错误:
- 直接将参数值硬编码进查询语句,未按照API文档要求使用GraphQL变量机制
- PHP单引号字符串中的
$ItemId不会被解析为实际变量值 - 错误的查询结构导致JSON编码后出现引号冲突,破坏了请求格式
正确的解决方案
按照GraphQL规范,需将查询语句和变量分开传递,以下是修正后的代码:
方案1:使用file_get_contents
$Tok = 'my token'; $Url = 'the api endpoint url'; $ItemId = '$book - 093121'; // 目标查询ID // 严格遵循API文档定义带变量占位符的GraphQL查询 $query = 'query product($id: IdInput!) { product(id: $id) { id ts visible title slug description stock allocated price productClass codiceIva discount weight details { ...ProductDetailFragment } } }'; // 定义查询所需的变量 $variables = ['id' => $ItemId]; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $Tok ]; $data = file_get_contents($Url, false, stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => $headers, // 同时传递查询语句和变量 'content' => json_encode([ 'query' => $query, 'variables' => $variables ]), ] ])); $responseContent = json_decode($data, true); echo json_encode($responseContent, JSON_PRETTY_PRINT);
方案2:使用CURL
$Tok = 'my token'; $Url = 'the api endpoint url'; $ItemId = '$book - 093121'; $query = 'query product($id: IdInput!) { product(id: $id) { id ts visible title slug description stock allocated price productClass codiceIva discount weight details { ...ProductDetailFragment } } }'; $variables = ['id' => $ItemId]; $authorization = "Authorization: Bearer $Tok"; $ch = curl_init($Url); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', $authorization ]); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ 'query' => $query, 'variables' => $variables ])); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $result = curl_exec($ch); if($result !== false) { echo "<pre>"; print_r(json_decode($result, true)); echo "</pre>"; } else { echo curl_error($ch); } curl_close($ch);
关键修正点说明
- GraphQL查询结构:严格匹配API文档定义,使用
$id作为变量占位符,在查询体中引用该变量 - 变量分离传递:将实际ID值放在
variables字段中单独传递,这是GraphQL的标准请求格式 - PHP字符串处理:通过数组传递变量,避免了字符串插值可能带来的转义错误
- JSON格式正确性:依赖
json_encode自动处理引号转义,确保请求体格式合法
内容的提问来源于stack exchange,提问作者Daniele
相关产品推荐
相关产品推荐

