ShadowAccount
ShadowAccount

Reputation: 321

Looping through API results for pagination

I'm trying to access some data via an API. Here's my current code:

$ch = curl_init("https://api.example.com/rest/1.3/analytics/affiliate/vendor/?account=xxxxx&select=EARNINGS_PER_HOP");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Page: 1', 'Accept: application/json', 'Authorization: XXXXX'));
$response = curl_exec($ch);
curl_close($ch);

if ($response) {
    $array = json_decode($response, TRUE);

    foreach ($array['rows']['row'] as $data) {
        $value = $data['data']['value']['$'];
        $dimension = $data['dimensionValue'];
        /// insert $value and $dimension into database
    }
}

I'm just trying to get some data from it an insert it into a MySQL database. My current code is technically working, but the API only displays the first 100 results.

If there's more than 100 results, it'll provide the data and give a header response of 206 Partial Content to let me know there's more results. To get the next page, I have to send Page: n in the header.

As you can see from the code above, I am sending Page: 1 in the header.

How can I check to see if a 206 response code is given and if it is, keep looping through until it reaches a 200 response code (the page number in the header would need to be increased for each loop)?

Upvotes: 0

Views: 597

Answers (1)

rootkonda
rootkonda

Reputation: 1743

You can put that code inside a function and then call that function with 'n' as parameter based on the response code you get. Did you try that ? you can get the response code using curl_getinfo option CURLINFO_RESPONSE_CODE or CURLINFO_HTTP_CODE.

Upvotes: 1

Related Questions