PHP和Curl:从多页卷曲请求中获取所有结果

时间:2017-10-23 09:51:05

标签: php loops curl

我正在尝试向API发出请求。问题是结果集中是否有超过50条记录。 API会将结果细分为'页面'每个50个记录。我想在保存到数据库之前获得包含所有结果的单个数组。以下是我的代码:

<?
$url = 'http://developer-api.bringg.com/partner_api/users';

$data_string = array(
 'access_token' => "<YOUR ACCESS TOKEN>",
 'timestamp' => date('Y-m-d H:i:s'),
 'company_id' => <YOUR COMPANY ID>,
 'page' => 3 //this is the page key that needs to be specified
);

$secret_key = "<YOUR SECRET KEY>";

$signature = hash_hmac("sha1", http_build_query($data_string), 
$secret_key);

$data_string["signature"] = $signature;

$content = json_encode($data_string);

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type:application/json',
'Content-Length: ' . strlen($content))
);

$json_response = curl_exec($ch);

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ( $status != 200 ) {
 die("Error: call to URL $url failed with status $status, response 
   $json_response, curl_error " . curl_error($curl) . ", curl_errno " . 
curl_errno($curl));
}

curl_close($ch);

$response = json_decode($json_response, true);
?>

我无法知道我的记录数量,因此我不知道如何动态更改页码。有没有办法我可以做多个请求,也许可以用循环更改页码,然后将所有结果存储在一个数组中。请帮助,我是阵列和卷曲的新手。

1 个答案:

答案 0 :(得分:1)

创建一个数组,其中包含您迄今为止收到的所有结果。

然后从第一页开始。获取结果。将此获取的结果与all results数组合并。然后将页面增加1.现在重复该过程,直到获得零结果。恭喜你,你得到了所有的结果。基本上

$results = array ();
while ( true ) {
    ++ $data_string ["page"];
    fetch ();
    if (empty ( $newResults )) {
        break; // zero results means we finished the last page, so break out of the loop.
    }
    array_push ( $results, $newResults );
}