分页的api请求,如何知道是否还有另一个页面? [英] paginated api request, how to know if there is another page?
问题描述
我正在创建一个使用第三方API的PHP类.该API的方法具有以下请求URL结构:
I am creating a PHP class that use a 3rd party API. The API has a method with this request URL structure:
https://api.domain.com/path/sales?page=x
其中"x"是页码.
每个页面返回50次销售,我需要为每个用户返回不确定数量的页面(取决于用户销售),并存储每次销售中的一些数据.
Each page return 50 sales and I need to return an undefined number of pages for each user (depending on the user sales) and store some data from each sale.
我已经创建了一些方法,这些方法可以从URL获取数据,解码并创建具有所需数据的新数组,但仅使用首页请求即可.
I have already created some methods that get the data from the URL, decode and create a new array with the desired data, but only with the first page request.
现在,我想创建一种方法来检查是否有另一个页面,如果有,请获取它并再次进行检查
Now I want to create a method that check if is there another page, and if there is, get it and make the check again
如何检查是否还有其他页面?以及如何创建一个循环来获取另一页(如果有的话)?
我已经有了这段代码,但是它创建了一个无限循环.
I have already this code, but it create an infinite loop.
require('classes/class.example_api.php');
$my_class = new Example_API;
$page = 1;
$sales_url = $my_class->sales_url( $page );
$url = $my_class->get_data($sales_url);
while ( !empty($url) ) {
$page++;
$sales_url = $my_class->sales_url( $page );
$url = $my_class->get_data($sales_url);
}
我不使用CURL,我使用file_get_content
.当我请求超出范围的页面时,会得到以下结果:
I don't use CURL, I use file_get_content
. When I request a page out of range, I get this result:
string(2) "[]"
json_decode
之后的另一个:
array(0) { }
推荐答案
在您的输入中,在while循环中,您更改了$ url(实际上保存了API调用返回的数据),并检查了其是否为空,如果我正确的话.
From your input, in the while loop, you change the $url (which actually holds the data return by the API call) and this is checked for emptiness, if I'm correct.
$url = $my_class->get_data($sales_url);
如果以上只是原始响应(因此,如果页面超出范围,则字符串"[]")将永远不会把empty("[]")设置为true.因此,我的猜测是get_data的返回值是此字符串,即使结果为空,它也应该是实际的array/json(即,我怀疑一旦收集了数据(例如在循环外),便会执行json_decode).
If the above is just the original response (so in case of page out of range a string "[]"), it will never get empty("[]") to true. So my guess is that the return value from get_data is this string, while it should be the actual array/json even if the result is empty (ie I suspect that you perform the json_decode once you have collected the data e.g. outside the loop).
如果是这种情况,我的建议是要么在循环中检查"[]"(例如,当($ url!=="[]")时),要么在循环内对响应数据进行解码($ url) = json_decode($ url)).
If this is the case, my suggestion would be to either check for "[]" in the loop (e.g. while ($url !== "[]")) or within the loop decode the response data ($url = json_decode($url)).
这篇关于分页的api请求,如何知道是否还有另一个页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!