Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Instagram APIで特定のユーザー+特定の#タグで抽出したjsonを取得(ajaxでのリクエスト・レスポンスを想定)
<?php
if(isset($GET_['num']) && $GET_['num']){
$num = (int)htmlspecialchars($_GET['num']);
}else{
$num = 10;
}
// ユーザネームから固有のuser_IDを取得する。
define("INSTAGRAM_ACCESS_TOKEN", ACCESS TOKEN);
// ユーザアカウント名
$user_account = ACCOUNT;
// ユーザアカウント名からユーザデータを取得する。
$user_api_url = 'https://api.instagram.com/v1/users/search?q=' . $user_account . '&access_token=' . INSTAGRAM_ACCESS_TOKEN;
$user_data = json_decode(@file_get_contents($user_api_url));
// 取得したデータの中から正しいデータを選出
foreach ($user_data->data as $user_data) {
if ($user_account == $user_data->username) {
$user_id = $user_data->id;
}
}
$photos = array();
$tags = Hash Tag;
// 特定ユーザの投稿データ最新5件を取得する
$photos_api_url = 'https://api.instagram.com/v1/tags/'.$tags.'/media/recent?access_token=' . INSTAGRAM_ACCESS_TOKEN . "&count=50";
$photos_data = json_decode(@file_get_contents($photos_api_url));
//処理する配列を任意の数にまとめる
$photos_data_sliced = array_slice($photos_data->data, 0, $num);
$data = array();
foreach ($photos_data_sliced as $photo) {
if($photo->user->id == $user_id){//ユーザーIDでフィルタリング
$photodata = array();
$photodata['url'] = $photo->images->low_resolution->url;
$photodata['link'] = $photo->link;
$text = preg_replace('/[##]+[A-Za-z0-9-_ぁ-ヶ亜-黑]+/', '',$photo->caption->text);//コメントから#タグ削除、お好みで
$text = mb_convert_encoding($text, "utf8", "auto");//ダブルでエンコーディング
$text = mb_convert_encoding($text, "utf8", "utf8");
$photodata['text'] = $text;
$ts = $photo->caption->created_time;
$date = new DateTime("@$ts");
$photodata['date'] = $date->format('Y/m/d');
$data[] = $photodata;
}
}
echo json_encode($data);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.