最近两天,我试图通过原始PHP显示我的Instagram个人资料中的照片。但是我遇到了这些错误。
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
我从instagram API创建了正确的身份验证。我请求的API clients access
有效(clientId, userId, accessToken
)。当我使用PHP失败时,我尝试使用JavaScript插件instafeedjs。现在它运作良好。这是我的PHP代码,如下所示: -
<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>
答案 0 :(得分:4)
我得到了解决方案。通过将JSON数据用作多维数组很简单。每种数据都可以在这个数组中使用。
<?php
$access_token = "My_Access_Token";
$photo_count = 9;
$json_link = "https://api.instagram.com/v1/users/self/media/recent/?";
$json_link .="access_token={$access_token}&count={$photo_count}";
$json = file_get_contents($json_link);
$obj = json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $json), true);
echo "<pre>";
print_r($obj);
echo "</pre>";
foreach ($obj['data'] as $post){
$pic_text = $post['caption']['text'];
$pic_link = $post['link'];
$pic_like_count = $post['likes']['count'];
$pic_comment_count=$post['comments']['count'];
$pic_src=str_replace("http://", "https://", $post['images']['standard_resolution']['url']);
$pic_created_time=date("F j, Y", $post['caption']['created_time']);
$pic_created_time=date("F j, Y", strtotime($pic_created_time . " +1 days"));
echo "<div class='col-md-4 item_box'>";
echo "<a href='{$pic_link}' target='_blank'>";
echo "<img class='img-responsive photo-thumb' src='{$pic_src}' alt='{$pic_text}'>";
echo "</a>";
echo "<p>";
echo "<p>";
echo "<div style='color:#888;'>";
echo "<a href='{$pic_link}' target='_blank'>{$pic_created_time}</a>";
echo "</div>";
echo "</p>";
echo "<p>{$pic_text}</p>";
echo "</p>";
echo "</div>";
}
?>
答案 1 :(得分:3)
您的API端点错误。 这是从Instagram获取最近的用户媒体的API:
https://api.instagram.com/v1/users/self/media/recent/?access_token=ACCESS-TOKEN
获取access_token所有者发布的最新媒体。
<强>参数强>
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 of media to return.
了解详情:https://www.instagram.com/developer/endpoints/users/#get_users_media_recent_self