Skip to content

Instantly share code, notes, and snippets.

@jpriebe
Created April 30, 2017 11:37
Show Gist options
  • Save jpriebe/8266150dcef22337b98d2353d30b107c to your computer and use it in GitHub Desktop.
Save jpriebe/8266150dcef22337b98d2353d30b107c to your computer and use it in GitHub Desktop.
Builds an HTML index of all Spotify playlists belonging to a particular user
#!/usr/bin/php -q
<?php
/**
* Builds an HTML index of all Spotify playlists belonging to a particular user;
* unfortunately, the API does not return folder information, so you can't
* structure the index according to folders.
*
* How to use:
* 1. go to https://developer.spotify.com/, log in, and create an app; you
* will need the Client ID and Client Secret
*
* 2. get your user ID: in the Spotify desktop application, click your name,
* and click the ellipses beneath your name on the user screen; select
* "Share" from the popup menu, and copy the URL to the clipboard.
* The numeric portion at the end is your user id.
*
* 3. download this script and save it on a system with PHP 5.5 or up
* (you will also need composer on this system: https://getcomposer.org/)
*
* 4. use composer to install spotify-web-api-php:
*
* composer require jwilsson/spotify-web-api-php
*
* 5. edit this script to put in the CLIENT_ID, CLIENT_SECRET, and USER_ID
*/
require 'vendor/autoload.php';
$user_id = USER_ID;
$client_id = 'CLIENT_ID';
$client_secret = 'CLIENT_SECRET';
$session = new SpotifyWebAPI\Session(
$client_id,
$client_secret
);
$api = new SpotifyWebAPI\SpotifyWebAPI();
$session->requestCredentialsToken();
$accessToken = $session->getAccessToken();
// Set the code on the API wrapper
$api->setAccessToken($accessToken);
retrieve_all_playlists ($api, $user_id);
function retrieve_all_playlists ($api, $user_id)
{
$offset = 0;
while (true)
{
$playlists = $api->getUserPlaylists($user_id, [
'limit' => 50,
'offset' => $offset,
]);
$playlists = $playlists->items;
$num_returned = count ($playlists);
if ($num_returned == 0)
{
break;
}
$offset += $num_returned;
foreach ($playlists as $p)
{
print <<<__TEXT__
<li><a href="{$p->external_urls->spotify}">{$p->name}</a></li>
__TEXT__;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment