Basic Usage

Simple examples to get you started with YTMusicAPI PHP.

Getting Song Information

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic();

// Get detailed song information
$song = $yt->get_song('kJQP7kiw5Fk');

echo "Title: " . $song->videoDetails->title . "\n";
echo "Author: " . $song->videoDetails->author . "\n";
echo "Duration: " . $song->videoDetails->lengthSeconds . " seconds\n";
echo "View Count: " . number_format($song->videoDetails->viewCount) . "\n";

// Check if it's actually music
$info = $yt->get_song_info('kJQP7kiw5Fk');
if ($info->music) {
    echo "This is a music track\n";
} else {
    echo "This is a video, not music\n";
}

Basic Search

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic();

// Search for music
$results = $yt->search("Radiohead Creep");

foreach ($results as $result) {
    echo "Type: " . $result->resultType . "\n";

    if (!empty($result->title)) {
        echo "Title: " . $result->title . "\n";
    }

    if (!empty($result->artist)) {
        echo "Artist: " . $result->artist . "\n";
    }
    
    if (!empty($result->artists)) {
        $artists = array_map(fn($artist) => $artist->name, $result->artists);
        echo "Artists: " . implode(", ", $artists) . "\n";
    }
    
    echo "---\n";
}

Advanced Searching

Examples of different search filters and scopes.

Search Suggestions

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic();

// Get simple suggestions
$suggestions = $yt->get_search_suggestions("rad");
foreach ($suggestions as $suggestion) {
    echo "- " . $suggestion . "\n";
}

// Get detailed suggestions with highlighting
$detailed = $yt->get_search_suggestions("rad", detailed_runs: true);

foreach ($detailed as $suggestion) {
    foreach ($suggestion->runs as $run) {
        echo $run->text;
    }
    echo "\n";
}

Browsing Content

Examples for browsing artists, albums, and other content.

Artist Information

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic();

// Get artist information
$artist = $yt->get_artist("UCR28YDxjDE3ogQROaNdnRbQ");

echo "Artist: " . $artist->name . "\n";
echo "Subscribers: " . $artist->subscribers . "\n";
echo "Description: " . $artist->description . "\n";

// Browse artist's albums
if ($artist->albums && $artist->albums->browseId) {
    $albums = $yt->get_artist_albums(
        $artist->albums->browseId, 
        $artist->albums->params
    );
    
    echo "\nAlbums:\n";
    foreach ($albums as $album) {
        echo "- " . $album->title . " (" . $album->year . ")\n";
    }
}

Album Information

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic();

// Get album information
$album = $yt->get_album("MPREb_pyQa1mky9hE");
$artists = array_map(fn($artist) => $artist->name, $album->artists);

echo "Album: " . $album->title . "\n";
echo "Artist: " . implode(", ", $artists) . "\n";
echo "Year: " . $album->year . "\n";
echo "Duration: " . $album->duration . "\n";
echo "Track Count: " . $album->trackCount . "\n";

echo "\nTracks:\n";
foreach ($album->tracks as $track) {
    $artists = array_map(fn($artist) => $artist->name, $track->artists);
    echo ($track->index ?? '') . ". " . $track->title . " - " . implode(", ", $artists) . "\n";
}

Library Management

Examples for managing your personal library. These require authentication.

Accessing Your Library

<?php
require "vendor/autoload.php";

// Initialize with authentication
$yt = new Ytmusicapi\YTMusic("browser.json");

try {
    // Get your account information
    $account = $yt->get_account();
    echo "Logged in as: " . $account->name . "\n";
    echo "Premium: " . ($account->is_premium ? "Yes" : "No") . "\n";
    
    // Get your playlists
    $playlists = $yt->get_library_playlists();
    echo "You have " . count($playlists) . " playlists\n";
    
    // Get your library songs
    $songs = $yt->get_library_songs(limit: 10);
    echo "Library songs (first batch):\n";
    foreach ($songs as $song) {
        $artists = array_map(fn($artist) => $artist->name, $song->artists);
        echo "- " . $song->title . " by " . implode(", ", $artists) . "\n";
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Liked Songs with Ordering

<?php
$yt = new Ytmusicapi\YTMusic("oauth.json");

// Get liked songs ordered by recently added
$liked_songs = $yt->get_library_songs(
    limit: 25, 
    order: "recently_added"  // 'a_to_z', 'z_to_a', 'recently_added'
);

echo "Your " . count($liked_songs) . " most recently liked songs:\n";
foreach ($liked_songs as $index => $song) {
    $artists = array_map(fn($artist) => $artist->name, $song->artists);
    echo ($index + 1) . ". " . $song->title . " - " . implode(", ", $artists) . "\n";
}

Rating Songs

<?php
$yt = new Ytmusicapi\YTMusic("browser.json");

// Like a song
$yt->rate_song("kJQP7kiw5Fk", "LIKE");
echo "Song liked!\n";

// Remove rating (set to indifferent)
$yt->rate_song("kJQP7kiw5Fk", "INDIFFERENT");
echo "Rating removed!\n";

// Dislike a song
$yt->rate_song("kJQP7kiw5Fk", "DISLIKE");
echo "Song disliked!\n";

Playlist Operations

Examples for creating and managing playlists.

Creating and Managing Playlists

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic("browser.json");

// Create a new playlist
$playlist_id = $yt->create_playlist(
    title: "My PHP Playlist",
    description: "Created with YTMusicAPI PHP",
    privacy_status: "PRIVATE"
);

echo "Created playlist: " . $playlist_id . "\n";

// Add songs to the playlist
$video_ids = ["kJQP7kiw5Fk", "dQw4w9WgXcQ"];
$result = $yt->add_playlist_items($playlist_id, $video_ids);
echo "Added " . count($video_ids) . " songs to playlist\n";

// Edit playlist details
$yt->edit_playlist(
    $playlist_id,
    title: "My Updated Playlist",
    description: "Updated description",
    privacyStatus: "PUBLIC"
);

echo "Playlist updated!\n";

// Delete playlist
$yt->delete_playlist($playlist_id);

echo "Playlist deleted!\n";

Copying Playlists

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic("browser.json");

// Get a public playlist
$source_playlist = $yt->get_playlist("PL4D51474AB7BE5595");

// Create a copy in your library
$new_playlist_id = $yt->create_playlist(
    title: "Copy of " . $source_playlist->title,
    description: "Copied from public playlist",
    privacy_status: "PRIVATE",
    source_playlist: "PL4D51474AB7BE5595"
);

echo "Created copy: " . $new_playlist_id . "\n";
echo "Copied " . $source_playlist->trackCount . " tracks\n";

Progressive Loading

Examples for loading large playlists with progress indicators.

Loading Liked Music with Progress

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic("oauth.json");

try {
    // Get initial batch without continuations
    $playlist = $yt->get_playlist("LM", get_continuations: false);
    $tracks = $playlist->tracks;
    $total_count = $playlist->trackCount;

    echo "Loading liked music playlist...\n";
    echo "Expected tracks: approximately " . $total_count . "\n";

    // Load remaining tracks with progress indicator
    while ($playlist->continuation) {
        $progress = round((count($tracks) / $total_count) * 100, 1);
        echo "Progress: " . $progress . "% (" . count($tracks) . " loaded)\n";

        $playlist = $yt->get_playlist_continuation("LM", $playlist->continuation);
        $tracks = array_merge($tracks, $playlist->tracks);
        
        // Optional: Add delay to avoid rate limiting
        usleep(100000); // 100ms delay
    }

    echo "Completed! Loaded " . count($tracks) . " tracks\n";

    // Display some tracks
    echo "\nFirst 5 tracks:\n";
    foreach (array_slice($tracks, 0, 5) as $track) {
        $artists = array_map(fn($artist) => $artist->name, $track->artists);
        echo "- " . $track->title . " by " . implode(", ", $artists) . "\n";
    }

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Podcast Examples

Working with podcasts and episodes.

Browsing Podcasts

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic();

// Get podcast information
$podcast = $yt->get_podcast("PL6NmnwdNzZJtKvy-7jRXLAPeen7O-wAoK");

echo "Podcast: " . $podcast->title . "\n";
echo "Author: " . $podcast->author->name . "\n";
echo "Episodes: " . count($podcast->episodes) . "\n";
echo "Description: " . $podcast->description . "\n";

echo "\nLatest episodes:\n";
foreach (array_slice($podcast->episodes, 0, 5) as $episode) {
    echo "- " . $episode->title . " (" . $episode->date . ")\n";
}

Episode Details

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic();

// Get detailed episode information
$episode = $yt->get_episode("nDnLSYCOg7E");

echo "Episode: " . $episode->title . "\n";
echo "Podcast: " . $episode->author->name . "\n";
echo "Published: " . $episode->date . "\n";
echo "Duration: " . $episode->duration . "\n";
echo "Playlist ID: " . $episode->playlistId . "\n";

if ($episode->description) {
    echo "Description: " . substr($episode->description->text, 0, 200) . "...\n";
}

Upload Management

Managing your uploaded music content.

Requirements: Song upload requires browser authentication and supports mp3, m4a, wma, flac, or ogg files under 300MB.

Viewing Uploaded Songs

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic("browser.json");

// Get uploaded songs
$uploaded_songs = $yt->get_library_upload_songs();

echo "You have " . count($uploaded_songs) . " uploaded songs\n";

foreach ($uploaded_songs as $song) {
    echo "- " . $song->title;
    
    if ($song->artists) {
        $artists = array_map(fn($artist) => $artist->name, $song->artists);
        echo " by " . implode(", ", $artists);
    }
    
    if ($song->album) {
        echo " (Album: " . $song->album->name . ")";
    }
    
    echo "\n";
}

Uploading Songs

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic("browser.json");                                

function discoverSimilarMusic($artist_name, $yt) {
    echo "Discovering music similar to: " . $artist_name . "\n";
    
    // Search for the artist
    $artists = $yt->search($artist_name, filter: "artists", limit: 1);
    if (empty($artists)) {
        echo "Artist not found\n";
        return;
    }
    
    $browseId = null;
    foreach ($artists as $artist) {
        if ($artist->artist !== $artist_name) {
            $browseId = $artist->browseId;
            break;
        }
    }
    
    if (!$browseId) {
        echo "No related artists found\n";
        return;
    }

    // Get artist information
     $artist_info = $yt->get_artist($browseId);
    echo "Found artist: " . $artist_info->name . "\n";
    
    // Get a popular song to create a radio playlist
    if (!empty($artist_info->songs)) {

        $song = $artist_info->songs->results[0];
        echo "Using song: " . $song->title . "\n";
        
        // Get radio playlist
        $radio = $yt->get_watch_playlist(
            videoId: $song->videoId, 
            radio: true, 
            limit: 20
        );
        
        echo "Generated radio playlist with " . count($radio->tracks) . " tracks:\n";
        foreach (array_slice($radio->tracks, 0, 10) as $track) {
            if ($track->artists) {
                $artists = array_map(fn($a) => $a->name, $track->artists);
                echo "- " . $track->title . " by " . implode(", ", $artists) . "\n";
            }
        }
    }
}

// Usage
discoverSimilarMusic("Radiohead", $yt);

$yt = new Ytmusicapi\YTMusic("browser.json");

try {
    // Upload a song (requires browser authentication)
    $result = $yt->upload_song("/path/to/my_song.mp3");
    
    if ($result === "STATUS_SUCCEEDED") {
        echo "Song uploaded successfully!\n";
    } else {
        echo "Upload failed: " . $result . "\n";
    }
    
} catch (Exception $e) {
    echo "Upload error: " . $e->getMessage() . "\n";
}

Error Handling

Best practices for handling errors and edge cases.

Comprehensive Error Handling

<?php
require "vendor/autoload.php";

function searchWithErrorHandling($query) {
    try {
        $yt = new Ytmusicapi\YTMusic();
        $results = $yt->search($query);
        
        if (empty($results)) {
            echo "No results found for: " . $query . "\n";
            return [];
        }
        
        return $results;
        
    } catch (Ytmusicapi\YTMusicUserError $e) {
        echo "User error: " . $e->getMessage() . "\n";
        return [];
    } catch (Ytmusicapi\YTMusicServerError $e) {
        echo "Server error: " . $e->getMessage() . "\n";
        echo "This might be a temporary issue, try again later.\n";
        return [];
    } catch (Exception $e) {
        echo "Unexpected error: " . $e->getMessage() . "\n";
        return [];
    }
}

// Usage
$results = searchWithErrorHandling("Nonexistent Song XYZ123");
if (!empty($results)) {
    foreach ($results as $result) {
        echo "Found: " . $result->title . "\n";
    }
}

Authentication Error Handling

<?php
function getLibraryWithAuth($auth_file) {
    try {
        $yt = new Ytmusicapi\YTMusic($auth_file);
        
        // Test authentication
        $account = $yt->get_account();
        echo "Successfully authenticated as: " . $account->name . "\n";
        
        // Get library content
        $playlists = $yt->get_library_playlists();
        return $playlists;
        
    } catch (Ytmusicapi\YTMusicUserError $e) {
        if (strpos($e->getMessage(), "authentication") !== false) {
            echo "Authentication failed. Please check your auth file.\n";
            echo "Run: php vendor/bin/setup-ytmusicapi browser\n";
        } else {
            echo "User error: " . $e->getMessage() . "\n";
        }
        return [];
    } catch (Exception $e) {
        echo "Error accessing library: " . $e->getMessage() . "\n";
        return [];
    }
}

// Usage
$playlists = getLibraryWithAuth("browser.json");

Advanced Examples

Complex workflows and advanced usage patterns.

Music Discovery Workflow

<?php
$yt = new Ytmusicapi\YTMusic("browser.json");

// Discover new music based on an artist
function discoverSimilarMusic($artist_name, $yt) {
    echo "Discovering music similar to: " . $artist_name . "\n";
    
    // Search for the artist
    $artists = $yt->search($artist_name, filter: "artists", limit: 1);
    if (empty($artists)) {
        echo "Artist not found\n";
        return;
    }
    
    $browseId = null;
    foreach ($artists as $artist) {
        if ($artist->artist !== $artist_name) {
            $browseId = $artist->browseId;
            break;
        }
    }
    
    if (!$browseId) {
        echo "No related artists found\n";
        return;
    }

    // Get artist information
     $artist_info = $yt->get_artist($browseId);
    echo "Found artist: " . $artist_info->name . "\n";
    
    // Get a popular song to create a radio playlist
    if (!empty($artist_info->songs)) {

        $song = $artist_info->songs->results[0];
        echo "Using song: " . $song->title . "\n";
        
        // Get radio playlist
        $radio = $yt->get_watch_playlist(
            videoId: $song->videoId, 
            radio: true, 
            limit: 20
        );
        
        echo "Generated radio playlist with " . count($radio->tracks) . " tracks:\n";
        foreach (array_slice($radio->tracks, 0, 10) as $track) {
            if ($track->artists) {
                $artists = array_map(fn($a) => $a->name, $track->artists);
                echo "- " . $track->title . " by " . implode(", ", $artists) . "\n";
            }
        }
    }
}

// Usage
discoverSimilarMusic("Radiohead", $yt);

Playlist Backup Tool

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic("browser.json");

function backupPlaylist($playlist_id, $yt) {
    try {
        $playlist = $yt->get_playlist($playlist_id);
        
        $backup = [
            'metadata' => [
                'title' => $playlist->title,
                'description' => $playlist->description ?? '',
                'track_count' => $playlist->trackCount,
                'duration' => $playlist->duration,
                'backed_up' => date('Y-m-d H:i:s')
            ],
            'tracks' => []
        ];
        
        foreach ($playlist->tracks as $track) {
            $artists = array_map(fn($artist) => $artist->name, $track->artists ?? []);
            
            $backup['tracks'][] = [
                'title' => $track->title,
                'artists' => $artists,
                'videoId' => $track->videoId ?? null,
                'duration' => $track->duration ?? null,
                'album' => $track->album->name ?? null
            ];
        }
        
        $filename = "playlist_backup_" . $playlist_id . "_" . date('Y-m-d') . ".json";
        file_put_contents($filename, json_encode($backup, JSON_PRETTY_PRINT));
        
        echo "Backup saved to: " . $filename . "\n";
        echo "Backed up " . count($backup['tracks']) . " tracks\n";
        
    } catch (Exception $e) {
        echo "Backup failed: " . $e->getMessage() . "\n";
    }
}

// Usage
backupPlaylist("PL8vf41kYtI07auIsrEmx6tFDmIFbFBY0k", $yt);

Charts Analysis

<?php
require "vendor/autoload.php";

$yt = new Ytmusicapi\YTMusic();

// Analyze global music trends
$charts = $yt->get_charts("ZZ"); // Global charts

echo "Global Music Trends\n";
echo "==================\n";

// Top artists
if (isset($charts['artists'])) {
    echo "\nTop Artists:\n";
    foreach (array_slice($charts['artists'], 0, 10) as $artist) {
        $trend = $artist['trend'] ?? 'neutral';
        $emoji = $trend === 'up' ? '📈' : ($trend === 'down' ? '📉' : '➡️');
        
        echo $artist['rank'] . ". " . $artist['title'] . 
             " (" . $artist['subscribers'] . " subscribers) " . $emoji . "\n";
    }
}

// Chart playlists
if (isset($charts['videos'])) {
    echo "\nChart Playlists:\n";
    foreach ($charts['videos'] as $chart) {
        echo "- " . $chart->title . " (ID: " . $chart->playlistId . ")\n";
    }
}

// US-specific genre charts
$us_charts = $yt->get_charts("US");
if (isset($us_charts['genres'])) {
    echo "\nUS Genre Charts:\n";
    foreach ($us_charts['genres'] as $genre) {
        echo "- " . $genre->title . "\n";
    }
}
Tip: Many examples use PHP 8.0+ named parameters for clarity. For older PHP versions, use positional parameters instead.
Rate Limiting: Be mindful of making too many requests quickly. Consider adding small delays between requests for large operations.