奇怪的Youtube搜索API行为

时间:2016-10-04 11:44:01

标签: php json youtube-data-api

使用youtube数据ip时,我无法检索视频ID。我可以使用所有其他字段但访问videoId字段时出错。下列:     https://www.googleapis.com/youtube/v3/search?key={api_key}&channelId=UCXuqSBlHAE6Xw-yeJA0Tunw&part=snippet,id&order=date&maxResults=2

返回

{
"kind": "youtube#searchListResponse",
"etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/ycDRkf40ZrOgEHl0cz-4b60EIFc\"",
"nextPageToken": "CAIQAA",
"regionCode": "GB",
"pageInfo": {
 "totalResults": 3510,
 "resultsPerPage": 2
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/HOEmnNQHjX9o0bjBMiW0ipFEyl0\"",
"id": {
"kind": "youtube#video",
"videoId": "dkDq3JJ6IvM"
},
"snippet": {
"publishedAt": "2016-10-04T07:05:26.000Z",
"channelId": "UCXuqSBlHAE6Xw-yeJA0Tunw",
"title": "Best All-around Gaming Laptop? - MSI GS63VR Review",
"description": "The GS63VR from MSI is our first GTX 1060-equipped gaming laptop. And man, are we impressed... TunnelBear message: TunnelBear is the easy-to-use VPN ...",
"thumbnails": {
 "default": {
  "url": "https://i.ytimg.com/vi/dkDq3JJ6IvM/default.jpg",
  "width": 120,
  "height": 90
 },
 "medium": {
  "url": "https://i.ytimg.com/vi/dkDq3JJ6IvM/mqdefault.jpg",
  "width": 320,
  "height": 180
 },
 "high": {
  "url": "https://i.ytimg.com/vi/dkDq3JJ6IvM/hqdefault.jpg",
  "width": 480,
  "height": 360
 }
},
"channelTitle": "LinusTechTips",
"liveBroadcastContent": "none"
}
},
{
"kind": "youtube#searchResult",
"etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/qXo91IDtZrS-0G5AOWB--t3pR4Y\"",
"id": {
"kind": "youtube#video",
"videoId": "g7UX0nP70E0"
},
"snippet": {
"publishedAt": "2016-10-03T06:50:31.000Z",
"channelId": "UCXuqSBlHAE6Xw-yeJA0Tunw",
"title": "The best retro gaming experience ever?",
"description": "Controllers are truly a dime a dozen nowadays... But do these retro-inspired controllers, and their wireless adapters, stand out from the pack? iFixit link: Use offer ...",
"thumbnails": {
 "default": {
  "url": "https://i.ytimg.com/vi/g7UX0nP70E0/default.jpg",
  "width": 120,
  "height": 90
 },
 "medium": {
  "url": "https://i.ytimg.com/vi/g7UX0nP70E0/mqdefault.jpg",
  "width": 320,
  "height": 180
 },
 "high": {
  "url": "https://i.ytimg.com/vi/g7UX0nP70E0/hqdefault.jpg",
  "width": 480,
  "height": 360
 }
},
"channelTitle": "LinusTechTips",
"liveBroadcastContent": "none"
}
}
]
}

现在,如果我     $videos = json_decode($result)

foreach($videos->items as $video)
    {
        print_r($video->id->videoId);

    }

我收到错误

   [ErrorException]
   Undefined property: stdClass::$videoId

然而 print_r($video->id->kind)会返回所需的结果

print_r($video->id)返回:

   stdClass Object
   (
   [kind] => youtube#video
   [videoId] => dkDq3JJ6IvM
   )

1 个答案:

答案 0 :(得分:0)

事实证明我上面的评论不是解决方案。

实际上foreach循环是出于某种原因的问题:

 foreach($videos->items as $video)
    {
        print_r($video->id->videoId);
    }

这不起作用并导致错误。只需用不同的单词(在本例中为项目)替换foreach循环中的$ video即可解决它:

foreach($videos->items as $item)
    {
        print_r($item->id->videoId);
    }