유튜브 채널 및 플레이리스트 rss 사용하기 > 그누보드5 팁자료실

그누보드5 팁자료실

유튜브 채널 및 플레이리스트 rss 사용하기 정보

유튜브 채널 및 플레이리스트 rss 사용하기

본문

유튜브에는 예전부터 채널아이디나 플레이리스트아이디를 통한 최신곡 15개씩을 rss 로 제공하고 있습니다.

 

https://www.youtube.com/feeds/videos.xml?channel_id=UCEf_Bc-KVd7onSeifS3py9g

 

https://www.youtube.com/feeds/videos.xml?playlist_id=RDCLAK5uy_k27uu-EtQ_b5U2r26DNDZOmNqGdccUIGQ

 

위에서 channel_id=UCEf_Bc-KVd7onSeifS3py9g

playlist_id=RDCLAK5uy_k27uu-EtQ_b5U2r26DNDZOmNqGdccUIGQ 를 보면 xml 의 꼬랑지만 바꾸면

원하는 채널과 플레이리스트의 rss 를 열어볼 수 있습니다.

 

이건 편하게 php 의 curl 로 긁어와야 합니다.

 


<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/feeds/videos.xml?channel_id=UCEf_Bc-KVd7onSeifS3py9g");    
$youtube_rss = curl_exec($ch);
curl_close($ch);
?>

 

제대로 긁어왔는지 확인하려면 긁어온 내용물을 textarea 에 넣어보는 것이 가장 간명합니다.

 


<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/feeds/videos.xml?channel_id=UCEf_Bc-KVd7onSeifS3py9g");    
$youtube_rss = curl_exec($ch);
curl_close($ch);
?>
<textarea><?php echo $youtube_rss; ?></textarea>

 

이제 원하는 문자열로 추출합니다.

지금부터 이 작업을 수행하기 위해서는 좋게 말하면 "내공"이... 나쁘게 말하면 "잔대갈빡"이 필요합니다.

수많은 방법들이 있겠지만... 저는 나만의 방식으로 처리했습니다.

저는 자바스크립트로 사용할 것이니 그에 맞게 바꾸어야겠죠.

str_replace 와 explode 를 이용하였습니다.

만일 php 가 아닌 자바스크립트로를 사용하여 이 방식으로 파싱하려면 replace 또는 split 나 join 등으로 문자열을 지지고 볶아야 하겠지요.

 


<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/feeds/videos.xml?channel_id=UCEf_Bc-KVd7onSeifS3py9g");    
$youtube_rss = curl_exec($ch);
curl_close($ch);
$youtube_id_replace = str_replace("</yt:videoId>", "<yt:videoId>", $youtube_rss);
$youtube_id_change = explode("<yt:videoId>", $youtube_id_replace);
$youtube_title_replace = str_replace("</media:title>", "<media:title>", $youtube_rss);
$youtube_title_change = explode("<media:title>", $youtube_title_replace);
$youtube_cut = 2;
for ($i = 1; $i < count($youtube_id_change); $i++) {
    if ($i % 2 === 1) {
        echo "ytList_".ceil($i / $youtube_cut)." = [\"".$youtube_id_change[$i]."\", \"".$youtube_title_change[$i]."\"];<br>";
    }
}
?>

 

코드를 실행하면 아래처럼 됩니다.

 


ytList_1 = ["nnqhF_H6-FE", "D.O. 디오 'Rose' MV Teaser"];
ytList_2 = ["_eprOE_CdEI", "KANGTA 강타 '자유롭게 날 수 있도록 2021 (Free To Fly 2021)' MV"];
ytList_3 = ["PtFnieJ7Imc", "SMCU the Origin"];
ytList_4 = ["3F2OaR4oHfM", "SM Leader Film"];
ytList_5 = ["RmuL-BPFi2Q", "TAEYEON 태연 'Weekend' MV"];
ytList_6 = ["IWFcspPYcfs", "KYUHYUN 규현 '투게더 (Together)' MV"];
ytList_7 = ["vblAjUXuhFs", "TAEYEON 태연 'Weekend' MV Teaser"];
ytList_8 = ["T-JA8REzMek", "KYUHYUN 규현 '투게더 (Together)' MV Teaser #2"];
ytList_9 = ["wrzgeVP3BZ8", "SHINee シャイニー 'SUPERSTAR' MV"];
ytList_10 = ["SsM4QeEdGEM", "[SM Entertainment Group] SM Congress 2021"];
ytList_11 = ["QPUjV7epJqE", "NCT DREAM 엔시티 드림 'Hello Future' MV"];
ytList_12 = ["R31AkjoSqmE", "KYUHYUN 규현 '투게더 (Together)' MV Teaser #1"];
ytList_13 = ["e6cPHOHoggk", "SHINee シャイニー 'SUPERSTAR' MV Teaser"];
ytList_14 = ["ba9Incui0oI", "NCT DREAM 엔시티 드림 'Hello Future' MV Teaser"];
ytList_15 = ["oGBQaOLAR0E", "WayV-KUN&XIAOJUN 'Back To You (English Ver.)' MV"];

 

주의사항이 있다면 이건 보이기 위하여 <br> 태그를 첨가하였는데 이건 빼주거나 \n 으로 바꾸어야 합니다.

 

그래서 최종적으로는...

 


<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/feeds/videos.xml?channel_id=UCEf_Bc-KVd7onSeifS3py9g");    
$youtube_rss = curl_exec($ch);
curl_close($ch);
$youtube_id_replace = str_replace("</yt:videoId>", "<yt:videoId>", $youtube_rss);
$youtube_id_change = explode("<yt:videoId>", $youtube_id_replace);
$youtube_title_replace = str_replace("</media:title>", "<media:title>", $youtube_rss);
$youtube_title_change = explode("<media:title>", $youtube_title_replace);
$youtube_cut = 2;
for ($i = 1; $i < count($youtube_id_change); $i++) {
    if ($i % 2 === 1) {
        echo "ytList_".ceil($i / $youtube_cut)." = [\"".$youtube_id_change[$i]."\", \"".$youtube_title_change[$i]."\"];\n";
    }
}
?>

 

채널아이디나 플레이리스트아이디를 겟변수로 빼면 웹페이지 주소의 물음표 뒤에 연결할 수 있으니 더욱 더 활용도가 높을 수 있습니다. 그리고 그 겟변수가 포함된 주소를 js 처럼 사용하면 되겠지요.

 

이것은 그누의 최신글처럼 업로드되는 실시간으로 동영상이 바뀝니다.

 

그리하여... https://sir.kr/g5_skin/46196 의 여분필드 없는 풀소스는 아래와 같습니다.

 


<script src=https://www.youtube.com/iframe_api></script>
<script>
ytString = 36; // 리스트최대문자열 - 0은 리스트모든문자열 
ytCut = 10; // 리스트갯수 - 0이나 15를 주면 최대 15개
ytGap = 5; // 간격픽셀값
<?php
$youtube_full_id = "channel_id=UCEf_Bc-KVd7onSeifS3py9g"; // 유튜브풀아이디
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/feeds/videos.xml?".$youtube_full_id);    
$youtube_rss = curl_exec($ch);
curl_close($ch);
$youtube_id_replace = str_replace("</yt:videoId>", "<yt:videoId>", $youtube_rss);
$youtube_id_change = explode("<yt:videoId>", $youtube_id_replace);
$youtube_title_replace = str_replace("</media:title>", "<media:title>", $youtube_rss);
$youtube_title_change = explode("<media:title>", $youtube_title_replace);
$youtube_cut = 2;
for ($i = 1; $i < count($youtube_id_change); $i++) if ($i % 2 === 1) echo "ytList_".ceil($i / $youtube_cut)." = [\"".$youtube_id_change[$i]."\", \"".$youtube_title_change[$i]."\"];\n";
?>
for (listTotal = 0; this['ytList_' + (listTotal + 1)]; listTotal++);
ytNumber = goMode = loadMode = 1;
if (ytCut > 0) listTotal = ytCut;
function listEffect() {
    for (var i = 1; i <= listTotal; i++) {
        if (i == arguments[0]) {
            if (ytString == 0) this["list_" + i].innerHTML = "<strong>" + this['ytList_' + i][1] + "</strong>";
            else this["list_" + i].innerHTML = "<strong>" + this['ytList_' + i][1].slice(0, ytString) + (this["ytList_" + i][1].length <= ytString ? "" : "...") + "</strong>";
            this["list_" + i].style.backgroundColor = '#f7d7e4'
        }
        else {
            if (ytString == 0) this["list_" + i].innerHTML = this['ytList_' + i][1];
            else this["list_" + i].innerHTML = this['ytList_' + i][1].slice(0, ytString) + (this["ytList_" + i][1].length <= ytString ? "" : "...");
            this["list_" + i].style.backgroundColor = '#eeeeee';
        }
    }
    listTitle.innerHTML = this['list_' + arguments[0]].innerHTML;
}
function ytGo() {
    if (arguments[0] == 'next') divPlayer.loadVideoById(this['ytList_' + (listNumber = listNumber == listTotal ? 1 : listNumber + 1)][0]), goMode = 1;
    else if (arguments[0] == 'prev') divPlayer.loadVideoById(this['ytList_' + (listNumber = listNumber == 1 ? listTotal : listNumber - 1)][0]), goMode = 0;
    else divPlayer.loadVideoById(this['ytList_' + (listNumber = arguments[0])][0]);
    divPlayer.playVideo();
    listEffect(listNumber);
}
function onYouTubeIframeAPIReady() {
    divPlayer = new YT.Player('iframePlayer', { events: {'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange} });
}
function onPlayerReady(event) {
    event.target.playVideo();
    if (loadMode) setTimeout(mediaMode, 1), delete loadMode;
}
function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED) ytGo(goMode ? 'next' : 'prev');
}
function mediaMode() {
    for (var i = 1; i <= listTotal; i++) {
        this['list_' + i].innerText = this['ytList_' + i][1];
        this['list_' + i].num = i;
        this['list_' + i].onclick = function() { ytGo(this.num); }
        this['list_' + i].onmouseover = function() { this.style.color='#c00000'; }
        this['list_' + i].onmouseout = function() { this.style.color='#000000'; }
    }
    this['list_' + ytNumber].onclick();
    titleTable.style.fontSize = listTable.style.fontSize = ("win16win32win64macmacintel").indexOf(navigator.platform.toLowerCase()) < 0 ? '13px' : '16px';
}
</script>
<style>
@import url(http://cdn.jsdelivr.net/font-nanum/1.0/nanumbarungothic/nanumbarungothic.css);
#divPlayer { position:relative; padding-bottom:56.25%; height:0px; overflow:hidden; max-width:100%; }
#iframePlayer { position:absolute; top:0px; left:0px; width:100%; height:100%; display:block; }
#titleTable { width:100%; color:#000000; font-family:'Nanum Barun Gothic'; padding:12px; background-color:#d5e6f9; border:1px solid #cccccc; }
.listTd { color:#000000; font-family:'Nanum Barun Gothic'; padding:12px; text-align:center; cursor:pointer; }
</style>
<div id=mediaDiv>
    <table id=titleTable cellpadding=0 cellspacing=0>
        <td style=text-align:left;cursor:pointer onclick=ytGo('prev') onmouseover=style.color='#c00000' onmouseout=style.color='#000000'>◀◀</td>
        <td id=listTitle style=text-align:center></td>
        <td style=text-align:right;cursor:pointer onclick=ytGo('next') onmouseover=style.color='#c00000' onmouseout=style.color='#000000'>▶▶</td>
    </table>
    <div id=divPlayer><script>document.write("<iframe id=iframePlayer src=https://www.youtube.com/embed/" + this['ytList_' + ytNumber][0] + "?autoplay=1&enablejsapi=1 frameborder=0 allowfullscreen></iframe>")</script></div>
    <table id=listTable style=width:100%;background-color:#cccccc cellpadding=0 cellspacing=1>
        <script>for (var i = 1; i <= listTotal; i++) document.write("<tr><td id=list_" + i + " class=listTd></td></tr>")</script>
    </table>
</div>
<script>divPlayer.style.marginTop = divPlayer.style.marginBottom = ytGap + 'px'</script>
추천
9

댓글 10개

매우 유용한 팁을 공개해주셔서 감사드립니다.
유튜브리스트 플레이어 게시판에서 유튜브영상을 표시할 때 youtube.php를 불러와서 표시하든데, 그 소스가 바로 이것이네요.
게시판에서 유뷰브보기 할 때도 유용하지만, 관련 유튜브 채널을 여러 개 보여주는 사이트에도 매우 유용하게 사용될 수 있을 것 같습니다.
비타주리님의 스킨, 팁, 플러그인은 모두가 정말 유용합니다.
감사합니다^^^
http://pws.co.kr/zz/youtube_curl_parsing.php
전체 126 |RSS
그누보드5 팁자료실 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT