下面介绍网多云GraphQL接口的三种常用场景:“遍历某数据源的所有数据”,“搜索某数据源符合条件的所有数据” 和 “获取列表+详情页数据”
遍历某数据源的所有数据
<?php
$user_key = '用户Key';
$user_secret = '用户密钥';
$source_id = <数据源ID>;
$cursor = 0; $has_next_page = false; $try = 0; do { $timestamp = time(); $sign = md5($user_key . $timestamp . $user_secret); $query = "source(__id:{gt:{$cursor}},limit:100,sort:\"asc\")". "{data{},page_info{end_cursor,has_next_page}}"; $url = "https://graphql.wangduoyun.com/?". "user_key={$user_key}×tamp={$timestamp}&sign={$sign}". "&source_id={$source_id}&query=" . urlencode($query);
$content = file_get_contents($url); $result = json_decode($content, true); if ($result && $result['code'] == 0) { $try = 0; $page_info = $result['result']['page_info']; $cursor = $page_info['end_cursor']; $has_next_page = $page_info['has_next_page']; $items = $result['result']['data']; foreach ($items as $item) { print_r($item); } } else { $try++; if ($try > 3) { echo "try too many times, cursor: {$cursor}\n"; break; } } if (!$has_next_page) { echo "no more data\n"; break; } } while(true);
|
搜索某数据源符合条件的所有数据
与 “遍历某数据源的所有数据” 的写法类似,只需调整query
查询语句,增加 字段筛选条件 即可。
获取列表+详情页数据
以 “获取某数据源列表页+详情页数据” 为例,以下是示例代码:
<?php
$user_key = '用户Key';
$user_secret = '用户密钥';
$source_id = <数据源ID>;
$cursor = 0; $has_next_page = false; $try = 0; do { $timestamp = time(); $sign = md5($user_key . $timestamp . $user_secret); $query = "source(__id:{gt:{$cursor}},limit:100,sort:\"asc\")". "{data{__id,weixin_id,title,author,publish_time,thumbnail}". ",page_info{end_cursor,has_next_page}}"; $url = "https://graphql.wangduoyun.com/?". "user_key={$user_key}×tamp={$timestamp}&sign={$sign}". "&source_id={$source_id}&query=" . urlencode($query);
$content = file_get_contents($url); $result = json_decode($content, true); if ($result && $result['code'] == 0) { $try = 0; $page_info = $result['result']['page_info']; $cursor = $page_info['end_cursor']; $has_next_page = $page_info['has_next_page']; $items = $result['result']['data']; foreach ($items as $item) { print_r($item); } } else { $try++; if ($try > 3) { echo "try too many times, cursor: {$cursor}\n"; break; } } if (!$has_next_page) { echo "no more data\n"; break; } } while(true);
|
获取到列表页数据后,通过每条数据对应的__id
可以得到详情页数据,以下是获取详情页数据的示例代码:
<?php
$user_key = '用户Key';
$user_secret = '用户密钥';
$source_id = <数据源ID>;
$id = <数据ID>;
$timestamp = time(); $sign = md5($user_key . $timestamp . $user_secret); $query = "source(__id:{eq:{$id}}){}"; $url = "https://graphql.wangduoyun.com/?". "user_key={$user_key}×tamp={$timestamp}&sign={$sign}". "&source_id={$source_id}&query=" . urlencode($query);
$content = file_get_contents($url); $result = json_decode($content, true);
if ($result && $result['code'] == 0) { print_r($result['result']['data'][0]); } else { echo "query fail"; }
|