使用PHP进行GraphQL查询与获取数据的步骤如下:
composer require webonyx/graphql-php
<?php
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'hello' => [
'type' => Type::string(),
'resolve' => function () {
return 'world';
}
]
]
]);
$schema = new Schema([
'query' => $queryType
]);
<?php
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
// 获取请求中的GraphQL查询字符串
$query = $_POST['query'];
try {
$result = GraphQL::executeQuery($schema, $query)->toArray();
echo json_encode($result);
} catch (Exception $e) {
echo json_encode([
'error' => [
'message' => $e->getMessage()
]
]);
}
<?php
$query = '{
hello
}';
$response = file_get_contents('http://localhost/graphql', false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode(['query' => $query])
]
]));
$data = json_decode($response, true);
print_r($data);
这样就可以使用PHP进行GraphQL查询与获取数据了。需要注意的是,GraphQL查询语句需要符合GraphQL的语法规范,可以通过GraphQL Playground等工具进行调试。