如何用PHP curl实现graphQL

osh3o9ms  于 2023-05-16  发布在  PHP
关注(0)|答案(1)|浏览(115)

我使用Insomnia来测试我的graphQL查询,对于这个查询,一切都很好。然而,迁移到PHP并没有成功,我的代码看起来像这样使用curl:

$data = array ("query" => "{
    viewer {
         zones(filter: { zoneTag: '" . $zone . "' }) {
            httpRequestsAdaptive(
                filter: {
                    datetime_geq: '2023-05-10T08:00:00Z'
                    datetime_lt: '2023-05-10T08:05:00Z'
                }
                limit: 10000
                orderBy: [
                    datetime_DESC
                ]
            ) {
                device: clientDeviceType
                clientIP: clientIP
            }
            }
        }
    }
");

$data = http_build_query($data);
$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = "Authorization: Bearer $token";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/graphql");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result_plans = curl_exec($ch);
$result_plans = json_decode($result_plans, true);

curl_close($ch);
$response = $result_plans;

当我运行脚本时,我得到以下消息:

failed to recognize JSON request: 'invalid character 'q' looking for beginning of value'

如何使用PHP curl运行此查询?

dojqjjoe

dojqjjoe1#

我现在还不能访问CF API,但我可以向您展示如何针对另一个API进行操作。诀窍是将查询构建为字符串,并使用原生GraphQL变量语法进行动态部分。
我认为这段代码本身就说明了一切,但如果您有任何问题,请告诉我。
添加的一件事是,我几乎总是需要头,所以我添加了来自here的代码。但是,请参阅一些潜在的警告。

$query = <<<'GRAPHQL'
query Film($filmId: ID) {
  film(filmID: $filmId) {
    episodeID
    openingCrawl
  }
}
GRAPHQL;

$variables = ['filmId' => "2"];

$payload = json_encode(['query' => $query, 'variables' => $variables], JSON_THROW_ON_ERROR);

$headers = ['Content-Type: application/json'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://swapi-graphql.netlify.app/.netlify/functions/index");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 1);

$response = curl_exec($ch);

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

echo $body;

相关问题