Last two days I was trying to display photos from my Instagram profile by raw PHP. But I'm getting these errors.
Notice: Trying to get property of non-object in E:\xampp7\htdocs\instagram\index.php on line 29
Warning: Invalid argument supplied for foreach() in E:\xampp7\htdocs\instagram\index.php on line 29
I created proper authentication from instagram API. My requested API clients access
is valid (clientId, userId, accessToken
). When I failed with PHP than I tried with a JavaScript Plugin instafeedjs. Now It’s working well. Here is my PHP code, given below:-
<body>
<?php
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/3550421370/media/recent/?access_token=MY_VALID_ACCESS_TOKEN_IS_HERE");
$result = json_decode($result);
foreach ($result->data as $post) {
if(empty($post->caption->text)) {
// Do Nothing
}
else {
echo '<a class="instagram-unit" target="blank" href="'.$post->link.'">
<img src="'.$post->images->low_resolution->url.'" alt="'.$post->caption->text.'" width="100%" height="auto" />
<div class="instagram-desc">'.htmlentities($post->caption->text).' | '.htmlentities(date("F j, Y, g:i a", $post->caption->created_time)).'</div></a>';
}
}
?>
</body>
Your API endpoint is wrong. This is the API to fetch recent media of an user from Instagram:
https://api.instagram.com/v1/users/self/media/recent/?access_token=ACCESS-TOKEN
Get the most recent media published by the owner of the access_token.
Parameters
access_token A valid access token.
max_id Return media earlier than this max_id.
min_id Return media later than this min_id.
count Count of media to return.
Read more: https://www.instagram.com/developer/endpoints/users/#get_users_media_recent_self