Search code examples
phphtmlinstagram-api

Get photos from a tag in Instagram


I created an application to get all the photos which are related to a specific tag. But it limit to 15 photos. How can I get the all the photos with username.

Here is the code...

<?php

function scrape_insta_hash($tag) {
    $insta_source = 
     file_get_contents('https://www.instagram.com/explore/tags/'.$tag.'/'); 
    $shards = explode('window._sharedData = ', $insta_source);
    $insta_json = explode(';</script>', $shards[1]); 
    $insta_array = json_decode($insta_json[0], TRUE);
    return $insta_array; 
}

    $tag = 'paris'; 
    $results_array = scrape_insta_hash($tag);
    //$limit = 7; 
    $limit = 15; 
    $image_array= array(); 

    for ($i=0; $i < $limit; $i++) { 

        $latest_array = $results_array['entry_data']['TagPage'][0]['graphql']['hashtag']['edge_hashtag_to_media']['edges'][$i]['node'];
        $image_data  = '<img height="150" width="150" src="'.$latest_array['thumbnail_src'].'">'; // thumbnail and same sizes 
        //$image_data  = '<img src="'.$latest_array['display_src'].'">'; actual image and different sizes 
        array_push($image_array, $image_data);
    }

foreach ($image_array as $image) {
        echo $image;
}

?>

Solution

  • To process all the returned data, change your for loop into a foreach loop:

    foreach ($results_array['entry_data']['TagPage'][0]['graphql']['hashtag']['edge_hashtag_to_media']['edges'] as $latest_array) {
        $image_data  = '<img height="150" width="150" src="'.$latest_array['node']['thumbnail_src'].'">'; // thumbnail and same sizes 
        //$image_data  = '<img src="'.$latest_array['display_src'].'">'; actual image and different sizes 
        array_push($image_array, $image_data);
    }
    

    (notice the change to the assignment of $image_data as well)

    You can still limit the number of results from this loop like this (just set $limit = 0; to not limit the output):

    $limit = 15;
    $count = 0;
    foreach ($results_array['entry_data']['TagPage'][0]['graphql']['hashtag']['edge_hashtag_to_media']['edges'] as $latest_array) {
        $image_data  = '<img height="150" width="150" src="'.$latest_array['node']['thumbnail_src'].'">'; // thumbnail and same sizes 
        //$image_data  = '<img src="'.$latest_array['display_src'].'">'; actual image and different sizes 
        array_push($image_array, $image_data);
        $count++;
        if ($count == $limit) break;
    }