我尝试使用API v3获取YouTube缩略图和视频ID并将其回显为HTML,但我需要同时回显两个变量。目前我有以下内容:
<?php
$url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=12&playlistId=UUDWdi7vjr3ac_z_VMMeiL_Q&key=*************************';
$data = file_get_contents($url);
if ((preg_match_all("/\"videoId\":\s*\"(.+)\"/", $data, $video_get) ) && (preg_match_all("/\"title\":\s*\"(.+)\"/", $data, $title_get) ) ) {
foreach (($video_get[1] as $videoid) && foreach ($title_get[1] as $title ) ){
echo ("<div id=\"video-thumb\" class=\"col-sm-6\"><img id=\"video-thumb-320180\" src=\"https://i.ytimg.com/vi/'.$videoid.'/mqdefault.jpg\"><div class=\"video-hover\"><img class=\"play-hover\" src=\"images/play.png\"></div><h2 class=\"video-title\"><i><a href=\"https://youtube.com/watch?v='.$videoid.'\">'.$title.'</a></h2></i></div>");
}
}
else {
echo ("Error fetching uploads!")
}
?>
然而,在尝试这个之后,我似乎无法使用foreach作为&amp;&amp;作为。这里的解决方案是什么?
答案 0 :(得分:1)
不确定为什么要尝试preg_match()
...但是这些数据是json,只是json_decode()
它已经完成了。
$url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=12&playlistId=UUDWdi7vjr3ac_z_VMMeiL_Q&key=AIzaSyBYG6nKkdddYT2NXg987kljPrKqsCVXcNQ';
/** data is in an array **/
$data = json_decode(file_get_contents($url), true);
foreach($data['items'] as $row) {
echo ("
<div id=\"video-thumb\" class=\"col-sm-6\">
<img id=\"video-thumb-320180\" src=\"https://i.ytimg.com/vi/".$row['snippet']['resourceId']['videoId']."/mqdefault.jpg\">
<div class=\"video-hover\">
<img class=\"play-hover\" src=\"images/play.png\">
</div>
<h2 class=\"video-title\">
<i><a href=\"https://youtube.com/watch?v=".$row['snippet']['resourceId']['videoId']."\">" . $row['snippet']['title']."</a></i>
</h2>
</div>");
}
回复(来自文档)
{
"kind": "youtube#playlistItemListResponse",
"etag": etag,
"nextPageToken": string,
"prevPageToken": string,
"pageInfo": {
"totalResults": integer,
"resultsPerPage": integer
},
"items": [
{
"kind": "youtube#playlistItem",
"etag": etag,
"id": string,
"snippet": {
"publishedAt": datetime,
"channelId": string,
"title": string,
"description": string,
"thumbnails": {
(key): {
"url": string,
"width": unsigned integer,
"height": unsigned integer
}
},
"channelTitle": string,
"playlistId": string,
"position": unsigned integer,
"resourceId": {
"kind": string,
"videoId": string,
}
},
"contentDetails": {
"videoId": string,
"startAt": string,
"endAt": string,
"note": string
},
"status": {
"privacyStatus": string
}
}
]
}