我一直在尝试使用一些PHP和HTML代码(带有一些js)来为我的网站创建一个'正在播放'的spotify查看器。我无法让它发挥作用。我已经尝试了所有的可能性,如重命名文件,更改HTML和PHP和JS版本,但似乎没有任何工作。下面是我的HTML代码(js)和PHP代码。
<script src="jquery-1.11.0.min.js"></script>
<!--Begin Spotify Scrobble-->
<SCRIPT TYPE="text/javascript">function get_spotify() {
$.ajax({
type: 'POST',
url: '/public_html/Spotify.php',
data: { request: 'true' },
success: function(reply) {
$('.now-playing').html("<p>" + reply + "</p>");
}
});
}
</script>
<!--End Spotify Scrobble-->
PHP
?php
// Account & API Account Information
$user = "USERNAME"; // <---- Your username goes here
$key = "KEY"; //<-- Your API key goes here
+
// The URL of the request to API Service
$url = "http://ws.audioscrobbler.com/2.0/? method=user.getrecenttracks&user=USERNAME&api_key=APIKEY&forma t=json";
+
// Enable Shortening
$short_titles = false;
+
// Setup cURL for request
$ch = curl_init( $url );
-// Options for cURL
$options = array(
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $options);
-// Execute cURL and save return to $json
+
+// Execute cURL
$json = curl_exec($ch);
-// Close the connection
curl_close($ch);
-// Decode JSON response to array.
$data = json_decode($json,true);
+
// Get only the latest track information
$last = $data['recenttracks']['track'][0];
+
// Is now playing attribute present?
if (isset($last['@attr']['nowplaying'])) {
- // Echo now playing information.
+
$output = "I am currently listening to " . $last['name'] . ' by ' . $last['artist']['#text'] . " on Spotify.";
+
if ($short_titles) {
$output = sTrim($output);
}
+
echo trim($output);
} else {
- // Collect info on when this was last played and get the current UNIX time.
$played = $last['date']['uts']; $now = time();
- // Get the difference
$diff = abs($now - $played);
- // format hours
+
+ // Time formatting
$hours = intval(intval($diff) / 3600);
- // format minutes
$minutes = intval(($diff / 60) % 60);
- // IF hours is empty(equal to zero)
+
+ // String formatting based on time
if (!empty($hours)) {
- if ($hours > 24) // Is it more than 1 day?
+ if ($hours > 24)
$time = "over a day ago";
else
$time = $hours . " hours and " . $minutes . " minutes ago";
} else
$time = $minutes . " minutes ago";
+
$output = "I last listened to " . $last['name'] . ' by ' . $last['artist'] ['#text'] . " $time on Spotify";
+
if ($short_titles) {
$output = sTrim($output);
}
+
echo trim($output);
}
+
exit();
function sTrim($output) {