Search code examples
phparraysjsondecodefile-get-contents

Extract image URLs from Instagram media feed with JSON and PHP


I am trying to extract the different image URLs from the Instagram media feed:

<?php
$insta = file_get_contents('https://www.instagram.com/apple/media/');
$json = json_decode($insta, true);
foreach($json->items->images as $instaimage){
echo $instaimage['url']['standard_resolution'];
}
?>

Warning: Invalid argument supplied for foreach()

Output from https://www.instagram.com/apple/media:

{"items": [{"id": "1595195862853610235_5821462185", "code": "BYjRi-Aj-r7", "user": {"id": "5821462185", "full_name": "apple", "profile_picture": "https://scontent-bru2-1.cdninstagram.com/t51.2885-19/s150x150/20635165_1942203892713915_5464937638928580608_a.jpg", "username": "apple"}, "images": {"thumbnail": {"width": 150, "height": 150, "url": "https://scontent-bru2-1.cdninstagram.com/t51.2885-15/s150x150/e35/21149363_134897580459546_4211564004683808768_n.jpg"}, "low_resolution": {"width": 320, "height": 320, "url": "https://scontent-bru2-1.cdninstagram.com/t51.2885-15/s320x320/e35/21149363_134897580459546_4211564004683808768_n.jpg"}, "standard_resolution": {"width": 640, "height": 640, "url": "https://scontent-bru2-1.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/21149363_134897580459546_4211564004683808768_n.jpg"}}, "created_time": "1504382187", "caption": {"id": "17887744828075147", "text": "\u201cI will do almost anything to get the shot I envision...

Solution

  • Hope this one will be helpful. There are few issues with your code.

    1. json_decode($insta,true) will give you an array instead of an object, because here you are passing second parameter as true.

    2. $json->items contains array of objects of items instead of single items key.

    $insta = file_get_contents('https://www.instagram.com/apple/media/');
    $json = json_decode($insta);
    foreach($json->items as $instaimage)
    {
        echo $instaimage->images->standard_resolution->url;
        echo PHP_EOL;
    }