php – How to get more than 1000 people who liked a post through the VK API?

Question:

Trying to get all users who likes.getList a likes.getList via likes.getList . But there is a limitation: you can only get 1000 people at once. And how to get all users, if there are, for example, 3500?

This is how I get the list of the first 1000 likes:

$res = file_get_contents('https://api.vk.com/method/likes.getList?t‌​ype=post&owner_id=-1‌​111&item_id=111&exte‌​nded=1&count=1000&of‌​fset=0'); 
$resp = json_decode($res, true); 
foreach($resp['response']['items'] as $val) { 
    echo $val['first_name'] . "<br>\n"; 
}

Answer:

A small function that works recursively, each time shifting the offset parameter by the required amount (by offset in the request + the number of already selected users count ) until an empty answer comes. This means it's time to break off the recursion.

However, there may still be an error response instead of a response . But this processing is on your conscience))

Also, indicate the version of the API, otherwise it may return the wrong data that you expect, or even return an error.

$count = 1000;
$offset = 0;
$apiVersion = 5.60;
$result = [];

getLikesData($result, $count, $offset, $apiVersion);

function getLikesData(&$output, $count, $offset, $apiVersion) { 
    $query = 'https://api.vk.com/method/likes.getList?type=post&owner_id=-1‌​111&item_id=111&extended=1&friends_only=0&v='.$apiVersion.'&count='.$count.'&offset='.$offset;
    $resp = json_decode(file_get_contents($query), true);

    if (!$resp['response'])
        return;

    $items = $resp['response']['items'];

    if (empty($items))          
        return; 

    foreach ($items as $item) {
        $output[] = $item;
    }

    getLikesData($output, $count, $offset + $count, $apiVersion);
}


echo '<pre>';
print_r($result);
echo '</pre>';

The function contains a loop for filling the resulting array in order. If you use array_push , it will run faster. However, the result set will contain an array of arrays.

This is what I mean … Choose what you need: lower speed, but in order, or higher speed, but then you will have to organize a double loop during the output.

Scroll to Top