我是PHP的新手。我正试图从api获取youtube视频详细信息。我的尝试是,
public static function get_statistics($id=""){
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/youtube/v3/videos?part=statistics&id='.$id.'&key=<api_key>');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
$items = $obj->items;
return $items;
}
google api输出
{
"kind": "youtube#videoListResponse",
"etag": "\"q5k97EMVGxODeKcDgp8gnMu79wM/3rwcD8mpPjKqGuWm_i6VncLIf8Y\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"q5k97EMVGxODeKcDgp8gnMu79wM/G0FH__iOsQSluyo6j8IQWdxgcCI\"",
"id": "TruIq5IxuiU",
"statistics": {
"viewCount": "19736248",
"likeCount": "119522",
"dislikeCount": "3710",
"favoriteCount": "0",
"commentCount": "22205"
}
}
]
}
如何从上面的输出中获取“viewCount”
答案 0 :(得分:0)
您可以使用简单的正则表达式和php preg_match函数(Php.net Pregmatch())获取viewcount:
这是一个例子:
$string = '{
"kind": "youtube#videoListResponse",
"etag": ""q5k97EMVGxODeKcDgp8gnMu79wM/3rwcD8mpPjKqGuWm_i6VncLIf8Y"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": ""q5k97EMVGxODeKcDgp8gnMu79wM/G0FH__iOsQSluyo6j8IQWdxgcCI"",
"id": "TruIq5IxuiU",
"statistics": {
"viewCount": "19736248",
"likeCount": "119522",
"dislikeCount": "3710",
"favoriteCount": "0",
"commentCount": "22205"
}
}
]
}';
preg_match('/viewCount": "(.*?)"/', $string, $viewCount );
$viewCount = $viewCount[1];
echo $viewCount;
答案 1 :(得分:0)
你应该使用google sdk for PHP。 设置起来很容易,它会给你回报对象。
可以在这里找到:https://developers.google.com/api-client-library/php/