PHP → How to take a YouTube Video from Facebook Graph API and convert it to an embed HTML 5 YouTube player

Tony Mucci
Code Kings
Published in
1 min readJan 6, 2015

--

So when you use the Graph API from Facebook you get a JSON return something similar to this:

{
“data”: [
{
“source”: “http://www.youtube.com/v/AeFHAttQuIY?autohide=1&version=3&autoplay=1",
“type”: “video”,
“message”: “Did you know? You can leave your limits with the #LamboHuracan on #ForzaHorizon2 for Xbox!”,
“full_picture”: “https://fbexternal-a.akamaihd.net/safe_image.php?d=AQDFKEuzZdwRbNta&bust=1&url=https%3A%2F%2Ffbcdn-sphotos-g-a.akamaihd.net%2Fhphotos-ak-xpa1%2Ft31.0-8%2Fs720x720%2F10838171_1056779374347682_8775251615557532677_o.png",
“id”: “227228333969461_1056779801014306",
“created_time”: “2015–01–06T16:00:03+0000",
“likes”: {
“data”: [
{
“id”: “527943903982238",
“name”: “Akki Doddamani”
}
],
“paging”: {
“cursors”: {
“after”: “NTI3OTQzOTAzOTgyMjM4",
“before”: “NTI3OTQzOTAzOTgyMjM4"
},
“next”: “https://graph.facebook.com/v2.2/227228333969461_1056779801014306/likes?limit=1&summary=true&after=NTI3OTQzOTAzOTgyMjM4"
},
“summary”: {
“total_count”: 1147
}
}
},

Then you can simply look for the type that is being posted, if its a video AND a YouTube video, you can use the following code to get the ID and then inject it into a iFrame for the HTML 5 YouTube Video Player.

//NOTE : $data is the data property from the JSON file after it has been JSON decoded.
<?php
if($data['type']=='video') {
if (preg_match('/youtube/i', $data['source'])) {
//Get YT ID
$start = strpos($data['source'], '/v/');
$end = strpos($data['source'], '?');
$length = $end - $start;
$yt_id = substr($data['source'], $start, $length);
$yt_id = explode('/v/', $yt_id);
$yt_id = $yt_id[1];
?>


<iframe width="640px" height="480px" src="https://www.youtube.com/embed/<?php echo $yt_id; ?>?autohide=1&version=3&autoplay=1">


--

--

Tony Mucci
Code Kings

Co-founder of SimpliCourt, dree, My Company Tools, and Eklect Enterprises