PHP网易云热评API
Yrh 苦逼后端

这是一个php版获取网易云热评的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php

/**
* 获取歌单随机一首歌曲id
*/
function music_list_id()
{
//歌单id
$id = '2493852196';
$data = file_get_contents('http://music.163.com/api/playlist/detail?id=' . $id);
$json = json_decode($data, true);
//获取长度
$count = count($json['result']['tracks']);
//生成0~count-1范围内的随机数
$random = mt_rand(0, $count );
return $json['result']['tracks'][$random]['id'];
}

/**
* curl_get函数
*/
function curl_get($url, $referurl = '')
{
if (empty($referurl)) {
$referurl = $url;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// 输出头
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//模拟常用浏览器的 useragent
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19');
// 不跟随跳转
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
//模拟来源网址
curl_setopt($ch, CURLOPT_REFERER, $referurl);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}

/**
* 根据歌曲id获取直链
*/
function song_url()
{
$id = music_list_id();
$api = 'http://music.163.com/song/media/outer/url?id=';
$url = $api . $id . '.mp3';
$data = curl_get($url);
// 正则取连接
preg_match_all('/Location:(.*?)\.mp3/', $data, $arr);
// 判断一下是否成功
if (!empty($arr[1][0])) {
$play = $arr[1][0];
return str_replace('http://', 'https://', trim($play) . '.mp3');
}
}

/**
* 根据音乐id获取热门评论
*/
function music_hot_comments()
{
$id = music_list_id();
$data = file_get_contents('http://music.163.com/api/v1/resource/comments/R_SO_4_' . $id);
$json = json_decode($data, true);
if ($json['total'] > 0) {
$arr= [
//歌曲id
'id' => $id,
//评论者
'user' => $json['hotComments'][0]['user']['nickname'],
//歌曲图片
'pic' => $json['hotComments'][0]['user']['avatarUrl'],
//评论内容
'content' => $json['hotComments'][0]['content'],
//歌曲url
'song_url' => song_url()
];
return $arr;
}
}
echo music_hot_comments();

 Comments