如何自动循环获取所有页面并在唯一的json中合并页面?

时间:2019-03-30 19:49:53

标签: php arrays json api curl

我需要获取JSON Multpages API响应并将结果合并为唯一的JSON。

API GET,每页返回50个集合。

我需要:

  1. 生成curl请求循环;
  2. 最后一页响应为空时中断循环;
  3. 将页面的Json响应合并为一个(唯一的)json响应;

我的工作PHP代码:

 $p = 1;

 $curl = curl_init();

 curl_setopt_array($curl, array(
     CURLOPT_URL => "https://demourl.com/api-v1/products/?page=' . $p . '",
     CURLOPT_RETURNTRANSFER => true,
     CURLOPT_ENCODING => "",
     CURLOPT_MAXREDIRS => 10,
     CURLOPT_TIMEOUT => 30,
     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
     CURLOPT_CUSTOMREQUEST => "GET",
     CURLOPT_POSTFIELDS => "",
     CURLOPT_COOKIE => "ckAPI=lkjk09je1iiw90q882388mfvufuiag6f5n4dodr4",
     CURLOPT_HTTPHEADER => array(
         "authorization: Basic Og==",
         "content-type: application/json",
         "x-api-key: 85f8287ae41o2o3j4h56u7ub3416a1f7d06b2c5",
         "x-app-key: m1n2b3v4v4qwrty0192of9mawo0LswostOjeXoW"
     ),
 ));

 $response = curl_exec($curl);

 $err = curl_error($curl);

 curl_close($curl);

 if ($err) {
     echo "cURL Error #:" . $err;
 } else {
     header('Content-type: Application/JSON');
     $j = json_decode($response);
     echo  json_encode($j, JSON_PRETTY_PRINT);
 }

我的代码工作正常,但是此代码没有生成循环。

请帮助我。谢谢。

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,但也找到了其他选择。

解决方案和工作代码如下:

<?php

// abre curl
$curl = curl_init();
$result = array();
$numberOfPages = 5;
for($i = 1; $i < $numberOfPages; $i++) {
    $url = sprintf("https://myurl.com/api-v1/products/?page=%d", $i);


curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_POSTFIELDS => "",
  CURLOPT_COOKIE => "ckreg=9df47237df410nknvufuiag6f5n4dodr4",
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic Og==",
    "content-type: application/json",
    "x-api-key: 1l2k3j3h4a0s9d8fg8g7gh7lkjasdfh",
    "x-app-key: 4z1x2c23v4b5n6n7mqwerpy0876lkbj"
  ),
));


$response = curl_exec($curl);

$err = curl_error($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {

 $j = json_decode($response, true);

 $result[] = $j;

}


}

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
 header('Content-type: Application/JSON');
$result_M = json_encode($result, JSON_PRETTY_PRINT);
print_r( $result_M ); 

}