Alex Lacayo
Alex Lacayo

Reputation: 1487

PHP Curl Pagination: A faster way?

I am wanting to retrieve all the media a user has liked with the Instagram API. Instagram currently returns around the last 300 liked media with the following endpoint:

GET /users/self/media/liked

Each call returns around 30 results, so I have approximately 10 pages to scan through with my curl function which takes about 10 seconds.

Is there a faster way to do this? I know curl_multi allows you to fire mu

public function fetchLikes() 
{
    $url = 'https://api.instagram.com/v1/users/self/media/liked?count=100&access_token=' . $access_token;

    while (isset($url) && $url != '') {  
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $jsonData = curl_exec($ch);
        curl_close($ch);

        $response = json_decode($jsonData);

        foreach ($response->data as $post) {

            echo $post->user->username . "<br>";
        }

        $url = $response->pagination->next_url;
    }
}

Upvotes: 3

Views: 3172

Answers (1)

blackarcanis
blackarcanis

Reputation: 542

Move your curl_init() function before the loop while, and move curl_close() after the while, even if it's not an obligation.

Upvotes: 2

Related Questions