The embed URL for a channel’s live stream is:
JavaScript
x
2
1
https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID
2
and it works but if I want to embed near at it a YouTube live chat for current streaming the URL that I use for the embed is:
JavaScript
1
2
1
https://www.youtube.com/live_chat?v=VIDEOID&embed_domain=DOMAINURL
2
The problem is this: for every new live stream the Video ID changes. So that the embedded code isn’t valid anymore and chat isn’t displayed for next streaming.I want a permanent URL live chat valid for all my YouTube streaming without change video id manually every time. How to resolve? Perhaps with a script in PHP or javascript that read current YouTube URL and replace video id in chat embed URL? thanks
Advertisement
Answer
You could get the video ID using PHP like this:
JavaScript
1
32
32
1
<?php
2
3
try {
4
$videoId = getLiveVideoID('CHANNEL_ID');
5
6
// Output the Chat URL
7
echo "The Chat URL is https://www.youtube.com/live_chat?v=".$videoId;
8
} catch(Exception $e) {
9
// Echo the generated error
10
echo "ERROR: ".$e->getMessage();
11
}
12
13
// The method which finds the video ID
14
function getLiveVideoID($channelId)
15
{
16
$videoId = null;
17
18
// Fetch the livestream page
19
if($data = file_get_contents('https://www.youtube.com/embed/live_stream?channel='.$channelId))
20
{
21
// Find the video ID in there
22
if(preg_match('/'VIDEO_ID': "(.*?)"/', $data, $matches))
23
$videoId = $matches[1];
24
else
25
throw new Exception('Couldn't find video ID');
26
}
27
else
28
throw new Exception('Couldn't fetch data');
29
30
return $videoId;
31
}
32