mardi 2 octobre 2018

(LARAVEL) Get data from all pages in Youtube Data Api

Currently im working on database seeding on Youtube Data Api V3. Everything going well until i try to get the data from all pages which are using "nextPageToken".

Here's my code,

class YoutubeSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    // Playlist 1
    $client = new Client();
    $res1 = $client->request('GET', 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId={PLAYLIST_ID}&key={API_KEY}');
    $result = json_decode($res1->getBody(),true); // Nak return api data dalam bentuk JSON
    $datas = $result['items'];

    // Playlist 2
    $client2 = new Client();
    $res2 = $client2->request('GET', 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId={PLAYLIST_ID}&key={API_KEY}');
    $result2 = json_decode($res2->getBody(),true); // Nak return api data dalam bentuk JSON
    $datas2 = $result2['items'];

    foreach (array_merge($datas, $datas2) as $data) {

    $client = new Client();
    $res3 = $client->request('GET', 'https://www.googleapis.com/youtube/v3/videos?fields=items(id,snippet(publishedAt,title,description,thumbnails(medium)),contentDetails(duration),statistics(viewCount))&part=snippet%2CcontentDetails%2Cstatistics&key={API_KEY}&id='.$data['snippet']['resourceId']['videoId']);
    $result = json_decode($res3->getBody(),true); // Nak return api data dalam bentuk JSON
    $datasdetails = $result['items'];

    foreach ($datasdetails as $datadetails) {

    Youtube::updateOrCreate(
      [
        'video_id' => $data['snippet']['resourceId']['videoId'],
      ],
      [
      'title' => $data['snippet']['title'],
      'date_published' => $data['snippet']['publishedAt'],
      'thumbnails' => $data['snippet']['thumbnails']['medium']['url'],
      'description' => $data['snippet']['description'],
      'duration' => $datadetails['contentDetails']['duration'],
      'views' => $datadetails['statistics']['viewCount'],
      'playlist' => $data['snippet']['playlistId'],
      'tags' => $data['snippet']['resourceId']['videoId'],
    ]
  );
  }
}
}
}

Based on my code, its shown that im trying to fetch videos data and import to mysql db and its working nicely. But, its just only fetch the data from first page. How to fetch the data from all pages using "nextPageToken" in just one seed?

I have tried many ways and its not giving me any solutions.

Hope you guys can help me out. Thanks. Sorry for my bad english!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire