【发布时间】:2023-03-05 17:15:01
【问题描述】:
下面的 JSON 结构显示了搜索结果的格式。您可以获取更多详情here
{
"kind": "youtube#searchResult",
"etag": etag,
"id": {
"kind": string,
"videoId": string,
"channelId": string,
"playlistId": string
},
"snippet": {
"publishedAt": datetime,
"channelId": string,
"title": string,
"description": string,
"thumbnails": {
(key): {
"url": string,
"width": unsigned integer,
"height": unsigned integer
}
},
"channelTitle": string,
"liveBroadcastContent": string
}
}
下面是我在 PHP 文件中获取值的代码。
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => $_GET['maxResults'],
));
foreach ($searchResponse['items'] as $searchResult) {
switch ($searchResult['id']['kind']) {
case 'youtube#video':
$videos[] = $searchResult;
break;
}
foreach ($videos as $video) {
echo $video['snippet']['title'];
}
我可以从这里获取标题标签,但是如何获取缩略图 url 字符串值。我尝试使用$video['snippet']['thumbnails']['key']['url']。
编辑:我只是直接执行了代码并将其作为响应。现在,我尝试以$video['snippet']['thumbnails']['high']['url'] 访问url 值。还是没有运气!!上面写着Warning: Illegal string offset 'high'。
{
"kind": "youtube#searchListResponse",
"etag": "\"X98aQHqGvPBJLZLOiSGUHCM9jnE/iTnovD87h4Y7nwPlTFtrcd7IEPY\"",
"nextPageToken": "CAEQAA",
"pageInfo": {
"totalResults": 118094,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"X98aQHqGvPBJLZLOiSGUHCM9jnE/d7ArhLqOVP8ys-9qfM5Mk0UTbH4\"",
"id": {
"kind": "youtube#video",
"videoId": "ixnBb9cyTkg"
},
"snippet": {
"publishedAt": "2014-04-09T16:58:02.000Z",
"channelId": "UC7rvhg8JyqjmD_D2BV5lzNQ",
"title": "Mahabharat 9 April 2014 Full Episode (Krishna Save Draupadi Maha Episode)",
"description": "Mahabharat 10 April Promo ( Pandavas Anger ) https://www.youtube.com/watch?v=pGWMzWf-h2s Mahabharat 9 April 2014 Full Episode.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/ixnBb9cyTkg/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/ixnBb9cyTkg/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/ixnBb9cyTkg/hqdefault.jpg"
}
},
"channelTitle": "1ColorsTV",
"liveBroadcastContent": "none"
}
}
]
}
【问题讨论】:
-
查看这个...我注意到的第一件事是使用 $_GET...这样做非常危险,它可能导致各种代码感染...最好是使用 filter_input(INPUT_GET,"q",FILTER_SANITIZE_STRING)
-
谢谢@patrick,我会记住这一点的。