PHP GraphQL语法错误使用file_get_contents发出查询

ie3xauqp  于 2023-02-28  发布在  PHP
关注(0)|答案(1)|浏览(121)

我尝试开发一个简单的php客户端,遇到了一些麻烦。我的代码如下:

$Tok = 'my token';
    $Url = 'the api endpoint url';
    $ItemId = '$book - 093121'; // This is the id I search for
    $headers = ['Content-Type: application/json', 'Authorization: Bearer ' . $Tok];
    $query = 'query product("id":"$ItemId")';
    $data = file_get_contents($Url, false, stream_context_create([
     'http' => [
      'method' => 'POST',
      'header' => $headers,
      'content' => json_encode(['query' => $query]),
     ]
    ]));
    $responseContent = json_decode($data, true);
    echo json_encode($responseContent);

运行脚本时,我收到以下信息:{"errors":[{"message":"Line 1 col 18: Syntax error"}]}
当然,我尝试了许多组合(在“id”和/或$ItemID上没有引号,结果总是一样的,也许有不同的“col”
API开发人员发布的文档指出:

query product($id: IdInput!) {
  product(id: $id) {
    id
    ts
    visible
    title
    slug
    description
    stock
    allocated
    price
    productClass
    codiceIva
    discount
    weight
    details {
      ...ProductDetailFragment
    }
  }
}

Variables
{"id": IdInput}

我甚至试过

$authorization = "Authorization: Bearer $Tok";
    $ch = curl_init($Url);  // inizializza l'oggetto con l'URL da utilizzare
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['query' => $query]));
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $result = curl_exec($ch);
    if($result !== false) {
        echo "<pre>";
        print_r($result);
        echo "</pre>";
//      echo json_decode($result);
    }
    else
        echo curl_error($ch);

    curl_close($ch);

结果是一样的。
json编码的字符串如下所示:
{“查询”:“查询产品(“编号”:“$book - 093121”)"}
列18对应于反斜线前面的“d
有谁能给予我个忙吗?先谢谢你了

tjvv9vkg

tjvv9vkg1#

最后我找到了正确的语法:
{“查询”:“查询产品($id:ID输入!){产品(ID:$id){ id ts可见标题slug描述股票分配价格产品类别代码Iva折扣权重} }",“变量”:{“id”:“$book - 093121”}}
其中“id,ts,visible... etc”是要从查询中获取的字段(类似于SQL查询)

相关问题