我是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;
}
谷歌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"
您可以使用一个简单的正则表达式和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;
您应该使用google sdk for PHP。它很容易设置,它会给你对象作为回报。
可在此处获取:https://developers.google.com/api-client-library/php/