Youtube channel URL to channel Id (PHP)

Viewed 2367

I am making a web app using the YT Api V3 and I need my users to input their YT channel URL. I want my PHP script to convert this URL to a channel Id (I built all my script with channel Id methods and I dont want to modify all the files).

My question is : In PHP, how can I convert a YouTube channel URL to a YouTube channel Id ?

2 Answers

A standard YouTube channel URL looks like this: https://www.youtube.com/channel/[channel-id]

You may use a function like this to parse the channel ID:

function parse_channel_id(string $url): ?string {
        $parsed = parse_url(rtrim($url, '/'));
        if (isset($parsed['path']) && preg_match('/^\/channel\/(([^\/])+?)$/', $parsed['path'], $matches)) {
                return $matches[1];
        }
        throw new Exception("{$url} is not a valid YouTube channel URL");
        return null;
}

To expand the answer from above onto YouTube user url and playlist url besides YouTube channel url:

YouTube channel ID:

url: www.youtube.com/channel/[channel_id]

YouTube rss: www.youtube.com/feeds/videos.xml?channel_id=[channel_id]

YouTube username:

url: youtube.com/user/[username]

YouTube rss: youtube.com/feeds/videos.xml?user=[username]

YouTube playlist:

url: youtube.com/playlist?list=[playlist_id]

YouTube rss: youtube.com/feeds/videos.xml?playlist_id=[playlist_id]

We can use proper regex for each, and get the ID or form correct YouTube rss url like this:

 function getYouTubeXMLUrl( $url, $return_id_only = false ) {

    $xml_youtube_url_base = 'https://www.youtube.com/feeds/videos.xml';
    $preg_entities        = [
        'channel_id'  => '\/channel\/(([^\/])+?)$', //match YouTube channel ID from url
        'user'        => '\/user\/(([^\/])+?)$', //match YouTube user from url
        'playlist_id' => '\/playlist\?list=(([^\/])+?)$',  //match YouTube playlist ID from url
    ];


    foreach ( $preg_entities as $key => $preg_entity ) {
        if ( preg_match( '/' . $preg_entity . '/', $url, $matches ) ) {
            if ( isset( $matches[1] ) ) {
                if($return_id_only === false){
                    return $xml_youtube_url_base . '?' . $key . '=' . $matches[1];
                }else{
                    return [
                        'type' => $key,
                        'id' => $matches[1],
                    ];
                }

            }
        }
    }

}

$url     = 'https://www.youtube.com/channel/UCBLAoqCQyz6a0OvwXWzKZag';
$xml_url = getYouTubeXMLUrl($url);

echo $xml_url; //outputs https://www.youtube.com/feeds/videos.xml?channel_id=UCBLAoqCQyz6a0OvwXWzKZag

$entity_id_array =  getYouTubeXMLUrl($url, true);

print_r($entity_id_array); // outputs Array ( [type] => channel_id [id] => UCBLAoqCQyz6a0OvwXWzKZag );
Related