Code not Printing playlist details
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Hi,
I have this code but whenever I submit a URL into the box, it should output the details of the playlist but nothing is showing. Can someone help please?
<?php
// Check if user has submitted the form
// Check if user has submitted the form
if ( isset( $_POST[ 'playlist_url' ] ) ) {
// Retrieve playlist ID from Spotify Playlist URL
$playlist_url = $_POST[ 'playlist_url' ];
$playlist_parts = explode( '/', parse_url( $playlist_url, PHP_URL_PATH ) );
$playlist_id = end( $playlist_parts );
// Spotify Web API endpoint for retrieving a playlist
$endpoint = "https://api.spotify.com/v1/playlists/{$playlist_id}";
// Set up cURL request with Spotify API credentials
$client_id = mdjm_get_option( 'spotify_api_key' );
$client_secret = mdjm_get_option( 'spotify_secret_key' );
$spc_init = curl_init();
curl_setopt( $spc_init, CURLOPT_URL, 'https://accounts.spotify.com/api/token' );
curl_setopt( $spc_init, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $spc_init, CURLOPT_POST, 1 );
curl_setopt( $spc_init, CURLOPT_POSTFIELDS, 'grant_type=client_credentials' );
curl_setopt( $spc_init, CURLOPT_HTTPHEADER, array( 'Authorization: Basic ' . base64_encode( $client_id . ':' . $client_secret ) ) );
$result = curl_exec( $spc_init );
$status_code = curl_getinfo( $spc_init, CURLINFO_HTTP_CODE );
if ( curl_errno( $spc_init ) ) {
$error_message = curl_error( $spc_init );
echo "cURL Error: " . $error_message;
} else {
// Decode the JSON response from Spotify
$data = json_decode( $result, true );
if ( $data === null ) {
echo "Error: Unable to decode the JSON response from Spotify.";
} else {
// Print the JSON response and status code to the screen
echo "<pre>";
echo "Status Code: " . $status_code . "\n";
echo json_encode( $data, JSON_PRETTY_PRINT );
echo "</pre>";
}
}
// Close cURL session
curl_close( $spc_init );
}
// Check for errors in the Spotify response
if ( isset( $data[ 'error' ][ 'message' ] ) ) {
$error_message = $data[ 'error' ][ 'message' ];
echo "Error: " . $error_message;
} else {
// Extract relevant details from playlist JSON
$name = $data[ 'name' ];
$description = $data[ 'description' ];
$tracks = $data[ 'tracks' ][ 'items' ];
// Print playlist details
echo "<h1>{$name}</h1>";
echo "<p>{$description}</p>";
// Loop through tracks and print track details
foreach ( $tracks as $track ) {
$track_name = $track[ 'track' ][ 'name' ];
$artists = array();
foreach ( $track[ 'track' ][ 'artists' ] as $artist ) {
$artists[] = $artist[ 'name' ];
}
$artist_name = implode( ', ', $artists );
echo "<p>{$track_name} by {$artist_name}</p>";
}
}
?>
Labels:
- Labels:
-
api
-
development
-
php
Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page