使用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等工具進行調試。