I am writing a program in PHP that retrieves the list of who a user is following on Instagram. The problem I have is that their API only returns 50 results per call, and the rest is paginated. I know that there is a 'next page' as the returned JSON has a pagination->next_url. Currently, the code I have gets the JSON and decodes it. Immediately afterwards, a call is made to get the next page using the URL from the first API call. Have a look:
function getFollows($url){
$client_id = "my client id";
//echo "A url: ".$url."</br>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/follows/?client_id='.$client_id.'&access_token='.$token;
$first_page = getFollows($url);
$second_page = getFollows($first_page->pagination->next_url);
What I would like to do instead is to check the JSON for a next url and make a call to the next_url. Then it would check the JSON from that url for a next url and repeat. All collected JSON would then be merged into one list which I can then iterate through to echo each individual person. My question is how can I for every time there is pagination, get the next url, merge the JSON and repeat until there are no more pages to go through.
I could keep making $third_page, $fourth_page, but then that is pointless if the user has more than four pages of followers and if they only have 10 followers for example.
I have tried using an if function to check if there is pagination and array_merge(), but to no avail. Maybe I was doing it wrong. Please can someone point me in the right direction.
Thanks,
-DH
you can take a ready-made code, there is a point with pagination- https://github.com/cosenary/Instagram-PHP-API