如何使用php在shopify rest api中创建分页 [英] How to create pagination in shopify rest api using php
本文介绍了如何使用php在shopify rest api中创建分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 php 中创建了 curl 以使用 shopify product rest API.现在我想在其中创建分页.
I created curl in php for use shopify product rest API. Now I want to create pagination in that.
如何创建?
Link: "<https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={next}, <https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={previous}"
如何使用链接?
谢谢
推荐答案
以下功能可以帮助您.在 Php/Laravel 中使用 API 获取数据
Below function can help you. to fetch data using API in Php/Laravel
public function request($method,$url,$param = []){
$client = new \GuzzleHttp\Client();
$url = 'https://'.$this->username.':'.$this->password.'@'.$this->domain.'/admin/api/2019-10/'.$url;
$parameters = [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
]
];
if(!empty($param)){ $parameters['json'] = $param;}
$response = $client->request($method, $url,$parameters);
$responseHeaders = $response->getHeaders();
$tokenType = 'next';
if(array_key_exists('Link',$responseHeaders)){
$link = $responseHeaders['Link'][0];
$tokenType = strpos($link,'rel="next') !== false ? "next" : "previous";
$tobeReplace = ["<",">",'rel="next"',";",'rel="previous"'];
$tobeReplaceWith = ["","","",""];
parse_str(parse_url(str_replace($tobeReplace,$tobeReplaceWith,$link),PHP_URL_QUERY),$op);
$pageToken = trim($op['page_info']);
}
$rateLimit = explode('/', $responseHeaders["X-Shopify-Shop-Api-Call-Limit"][0]);
$usedLimitPercentage = (100*$rateLimit[0])/$rateLimit[1];
if($usedLimitPercentage > 95){sleep(5);}
$responseBody = json_decode($response->getBody(),true);
$r['resource'] = (is_array($responseBody) && count($responseBody) > 0) ? array_shift($responseBody) : $responseBody;
$r[$tokenType]['page_token'] = isset($pageToken) ? $pageToken : null;
return $r;
}
该函数的使用示例
$product_ids = [];
$nextPageToken = null;
do{
$response = $shop->request('get','products.json?limit=250&page_info='.$nextPageToken);
foreach($response['resource'] as $product){
array_push($product_ids, $product['id']);
}
$nextPageToken = $response['next']['page_token'] ?? null;
}while($nextPageToken != null);
如果你想在 php/laravel 中使用 graphQL api 那么下面的帖子可以帮助你
If you want to use graphQL api in php / laravel then below post can help you
如何请求 shopify graphql-admin-api 来自 api?
这篇关于如何使用php在shopify rest api中创建分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文