我试图从Spotify获取一些数据,因为他们最近改变了他们的API我写了一个遵循新指令的新功能:
function get_Spotify() {
$getTrackID = $this->db->query("SELECT `trackid` FROM `spotify` ORDER BY RAND() LIMIT 1");
$TrackID = $getTrackID->fetch_assoc();
$id=$TrackID['trackid'];
$client_id = '********************';
$client_secret = '**********************';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token' );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials' );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($client_id.':'.$client_secret)));
$result=curl_exec($ch);
$result = json_decode($result, true);
curl_close($ch);
//find spotify data
$spotifyURL = 'https://api.spotify.com/v1/tracks/'.$id;
$authorization = 'Authorization: Bearer '.$result["access_token"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_URL, $spotifyURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$json = curl_exec($ch);
$json = json_decode($json, true);
curl_close($ch);
$spotifyURL_artist = $json['artists'][0]['href'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_URL, $spotifyURL_artist);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$json_artist = curl_exec($ch);
$data_artist = json_decode($json_artist, true);
curl_close($ch);
$Spotify_Player = '
<div class="container-playerspot">
<div class="playerspot">
<div class="bg_spotify" style="background:url('.$data_artist['images'][0]['url'].');"><div class="ert-spotify"></div></div>
<ul class="player_spot-info info-one">
<li>'.$json['artists'][0]['name'].'</li>
<li>'.$json['name'].'</li>
</ul>
<ul class="player_spot-info info-two">
<li>'.$json['artists'][0]['name'].'</li>
<li>'.$json['name'].'</li>
<li><span id="duration"></span><i> / </i>0.30</li>
</ul>
<audio id="audio-player_spot" ontimeupdate="SeekBar()" ondurationchange="CreateSeekBar()" preload="none" loop>
<source src="'.$json['preview_url'].'" type="audio/mpeg">Your browser does not support the audio element.
</audio>
</div>
</div>';
return $Spotify_Player;
}
但我的网页加载速度很慢,因此在调查使用microtime()
后,我发现此功能(get_Spotify()
)需要 300毫秒。
我的代码有什么问题会导致这样一个灾难性的后果吗?
P.S。
MySQL表实际上只有4个结果,所以我排除了我的查询可能的原因。