PHP怎么使用GraphQL查询与获取数据


使用PHP进行GraphQL查询与获取数据的步骤如下:

    安装相关的PHP GraphQL库,推荐使用Webonyx GraphQL PHP库。可以通过Composer进行安装:
composer require webonyx/graphql-php
    创建GraphQL查询的schema,定义数据类型和查询字段。
<?phpuse 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]);
    处理GraphQL查询请求,并执行查询。
<?phpuse 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()]]);}
    发送GraphQL查询请求,获取数据。
<?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等工具进行调试。


上一篇:PHP怎么使用WebSocket实时推送与获取数据

下一篇:C#变量在集成测试与系统测试中怎么应用


php GraphQL
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器