dpv21589 2017-10-23 09:51
浏览 60
已采纳

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

I am trying to make a request to an API. The problem is if there are more than 50 records in the result set. The API will break down the result into 'pages' of 50 records each. I am trying to get a single array that has all the results before I save into the database. Below is my code:

<?
$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);
?>

I can not know the number of records I have so I don't know how to dynamically change the page number. Is there a way I can do multiple requests and maybe change the page number with loops and then store all the results in one array. Please help, I am new to arrays and curl.

  • 写回答

1条回答 默认 最新

  • doulingqiu4349 2017-10-24 02:10
    关注

    make an array that holds all results you've recieved thus far.

    then start on the first page. fetch the results. merge the results of this fetch with the all results array. then increase the page by 1. now repeat that process, until you get zero results in a fetch. congratulations, you got all the results. basically

    $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 );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵