Replace YouTube Links in Text with Embed Code (and Retrieve Video Details via the JSON API)

One of my websites (at Usenet.com.au) is based on rendering threaded text Usenet newsgroups. The text itself within the post body is very static and forces visitors to leave the website to explore links and content suggested by others. Part of the massive revamp of that website involves rendering those static links into dynamic elements. This includes – but is far from limited to – making YouTube links more dynamic… and doing so forms the basis of this post.

Consider this text:

As part of an aviation media venture, we recorded various Boeing 777 test footage in different situations. We took several hours of video in a Boeing 777 simulator to determine the most effective means of communicating various principles. Take, for example, this video that illustrates part of the pre-takeoff safety brief. After purchasing a few GoPro cameras, our initial camera tests were conducted simply by attaching the unit to the quarter windows of an aircraft. Here is an approach into LAX, while this is an approach into Sydney (http://youtu.be/T4eZ24ZjRgE). The next stage of our 777 Video Series is due to commence early September.

Because the output of this text is to be rendered in a text newsgroup, there are a few things I wanted to do:

  • I was required to strip any HTML but retain the anchor text in the code. For example, I wanted to convert <a href="http://www.youtube.com/watch?v=lxo2SlrxUYg">LAX</a> into LAX [http://www.youtube.com/watch?v=lxo2SlrxUYg].
  • I wanted to load all the YouTube links into an array (identified by http://www.youtube.com/watch?v=thisisthevidid or http://youtu.be/thisisthevidid). Based on that array, I wanted to render each unique video on the screen under the text body.
  • Based on the video ID of each unique video, I wanted to query the YouTube API and extract video details (notable author, description, title and length).
  • Because I didn’t want to repeatedly query the YouTube API for each page load, I would cache the video details for a specified period of time (not discussed in this post).

Change Links to Text and Retain Anchor Text in Brackets

The following expression finds links and converts them to text while retaining the anchor text in brackets. It’s a little outside the scope of this post but I’m sure somebody will find it useful.

$content = preg_replace('#]href="([^"]+)">([^<]+)#', "$2 [$1]", $content);

The above text will output as follows:

As part of an aviation media venture, we recorded various Boeing 777 test footage in different situations. We took several hours of video in a Boeing 777 simulator to determine the most effective means of communicating various principles. Take, for example, this video [http://www.youtube.com/watch?v=B1a6VddQgxA] that illustrates part of the pre-takeoff safety brief. After purchasing a few GoPro cameras, our initial camera tests were conducted simply by attaching the unit to the quarter windows of an aircraft. Here is an approach into LAX [http://www.youtube.com/watch?v=lxo2SlrxUYg], while this is an approach into Sydney (http://youtu.be/T4eZ24ZjRgE). The next stage of our 777 Video Series [http://www.youtube.com/watch?v=B1a6VddQgxA] is due to commence early September.

It’s far from a perfect expression so I’ll update it when I figure something else out.

Find YouTube Videos and Create an Array

By parsing the text body I can extract each YouTube video reference.

$content = preg_match_all('#https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/|youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>|))[?=&+%\w-]*#ix',$content,$output);

The $output array will look like this:

Array
(
  [0] => Array
     (
        [0] => http://www.youtube.com/watch?v=B1a6VddQgxA
        [1] => http://www.youtube.com/watch?v=lxo2SlrxUYg
        [2] => http://youtu.be/T4eZ24ZjRgE
        [3] => http://www.youtube.com/watch?v=B1a6VddQgxA
     )

  [1] => Array
     (
        [0] => B1a6VddQgxA
        [1] => lxo2SlrxUYg
        [2] => T4eZ24ZjRgE
        [3] => B1a6VddQgxA
     )

)

Note that the expression found the same video twice. We’ll take care of that shortly. In essence, you could do whatever you wanted to with the results that the expression returns. It’s at this point that I wanted to loop through each element of the array and either 1) render each video with embed code, or 2) display video details with a thumbnail.

Render YouTube Videos from Array

If all I wanted to do was render the embed code of each video we found under the text body, I could use the following:

foreach ($output[1] AS $video_id) {
    if (!isset($video[$video_id])) {
    $video[$video_id]=true;
    $embed_code = '<center><object width="420" height="236"><param name="movie" value="http://www.youtube.com/v/'.$video_id.'&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'.$video_id.'&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="420" height="236"></embed></object></center><br><br>';
  echo $embed_code;
 }
}

Note that the code will only output each video once only. The above code will embed each video on the page as follows:

YouTube Videos Embedded into Page

YouTube Videos Embedded into Page

Extract Additional Details from the YouTube API

The YouTube API is awesome and there isn’t much it won’t allow you to do. All we want to do in this case, however, is obtain the video thumbnail, title, views, description, author and length.

The following (rough, unstyled) code will extract those elements:

foreach ($output[1] AS $video_id) {
    if (!isset($video[$video_id])) {
    $video[$video_id]=true;

    // Get YouTube data via the API
	$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos?q=$video_id&alt=json");
	$JSON_Data = json_decode($JSON);
	$views = $JSON_Data->{'feed'}->{'entry'}[0]->{'yt$statistics'}->{'viewCount'};
	$title = $JSON_Data->{'feed'}->{'entry'}[0]->{'title'}->{'$t'};
	$duration = $JSON_Data->{'feed'}->{'entry'}[0]->{'media$group'}->{'yt$duration'}->{'seconds'};
	$description = $JSON_Data->{'feed'}->{'entry'}[0]->{'media$group'}->{'media$description'}->{'$t'};
	$video_author = $JSON_Data->{'feed'}->{'entry'}[0]->{'author'}[0]->{'name'}->{'$t'};

	echo "<img src='http://img.youtube.com/vi/$video_id/1.jpg'>&nbsp;<img src='http://img.youtube.com/vi/$video_id/2.jpg'>&nbsp;<img src='http://img.youtube.com/vi/$video_id/3.jpg'><br>";
	echo "<strong>Views</strong> $views<br><strong>Title</strong> $title<br><strong>Duration</strong> $duration<br><strong>Description</strong> $description<br><strong>Author</strong> $video_author<br><br>";

    }
}

Note: If you choose to look at the data returned by the API, you may want to post it into our JSON Validator to make it more readable.

Note: It’s the data above that you will want to cache in one way or another. You don’t want to make repeated requests to the YouTube API for the same information, over and over.

Note that we’re using a standard format to retrieve the video thumbnails rather than using the API. I’ve done this for no particular reason. [See this post on inserting thumbnails in your WordPress posts with shortcode!] Once you have the data, you can style video containers as you see fit on your page. See my very basic example below.

 ▸ Boeing 777 Arrival into Sydney (YSSY) Runway 25

Description: We’re testing the GoPro Hero2 for use as a means to capture various types of in-flight footage for use in training material. The HERO2 was mounted on the second right window…
Author: flightorg Length: 3m 36s

 ▸ Boeing 777 Simulator – Takeoff Safety Brief

Description:This is some *raw* footage for an upcoming Boeing 777 video training series. To be advised of when it becomes available, please subscribe to our mailing list at www.flight.org…
Author: flightorg Length: 1m 22s

 ▸ Boeing 777 Arrival into LAX Runway 25L

Description:We’re testing the GoPro Hero2 for use as a means to capture various types of in-flight footage for use in training material. The HERO2 was mounted on the second right window…
Author: flightorg Length: 5m 14s

It’s likely that when I implement this into my other website (that inspired this post) I’ll use something similar to above and link to a popup video container.

Suggested Usage

It’s likely that you have seen this kind of functionality before. Twitter uses a similar feature to render a YouTube video under each tweet with a link that resolves to a YouTube video. Facebook will render a video container if your ‘status update’ includes a YouTube link. We’re seeing it more and more as website owners appreciate the higher conversions and loyalty earned by negating the need to leave a page to view other types of content.

I wrote a quick WordPress plugin (that I’ll probably post soon) that’ll embed a video into a WordPress comment if it includes a link to a YouTube video. There are countless uses for this kind of PHP function!

Other PHP Functions

I was required to employ a few other functions to ensure I could format my content as chosen. First, I needed to truncate the video description so it didn’t consume too much of the page. You can download a function that’ll accomplish this here.

The YouTube API returns time in seconds that you may choose to convert to H:M:S. Here’s a sample PHP function that will do that for you:

  function sec2hms ($sec, $padHours = false) 
  {
    $hms = "";
    $hours = intval(intval($sec) / 3600); 
    $hms .= ($padHours) 
          ? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"
          : $hours. ":";
    $minutes = intval(($sec / 60) % 60); 
    $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";
    $seconds = intval($sec % 60); 
    $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
    return $hms;
}

Usage: echo sec2hms(82);

First Name:
Your Email Address:
 




Download: Convert YouTube links to Embed Code
Description: Convert YouTube links to Embed Code. Extract data from the YouTube API.
Author:Marty
Category: PHP code
Date: July 22, 2012



If you liked this article, you may also like:

  1. Get YouTube Views with PHP or WordPress Shortcode
  2. Add Thumbnail Image (Links) from a YouTube RSS Feed to WordPress with Shortcode
  3. Insert YouTube Subscriber Count or Video Views in WordPress with Shortcode
  4. [Shortcode] Insert Youtube videos into your blog with shortcode
  5. YouTube Thumbnails in WordPress Posts with Shortcode
About Marty

is a passionate web developer from Sydney, Australia. He owns about 600 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. Follow Marty on Twitter or Google+.

Comments

  1. bivouac says:

    Thanks for sharing your youtube code. it will come in handy and glad i found it.
    Regards

  2. jim says:

    Extract Additional Details from the YouTube API – the one with the image on the left and then the details on the right. I’d love a wordpress coded version of this that is based on pulling this data from a videoid. Any chance you could post it?

Trackbacks

  1. [...] detailed in other posts, YouTube provides four thumbnail images for each video; three small images (120×90) and [...]

Speak Your Mind

*