Youtube URL to Embed Code

Posted by Tully on Mon 07 December 2009

Working on a new site and wanted to add a function to add embed code from YouTube. I am limiting the amount of html that is allowed to be posted by the users. I also wanted to make sure the user could only embed a video from YouTube. The function I'm working on takes the URL of the YouTube page and parses the source for the embed code. Below is an example on how I am getting the data. The actual function does a lot more filtering of the URL string.

Retrieve YouTube Embed Tag

<p>
    <form action="#" method="get">
        <input type="text" name="url" value="YOUTUBE URL">
        <input type="submit" name="submit" value="Get Embed Code">
    </form>
</p>

<?php
if ($_GET['url'] != "") {
    $url = file_get_contents($_GET['url']);
    $url = preg_match('/(input id="embed).*(\/>)/', $url, $arr);
    $url = preg_match('/(&lt;).*(\/object&gt;)/',$arr[0], $result);

    $result = html_entity_decode($result[0]);

    echo '<b>The Video...</b><br />';
    echo $result . '<br /><br />';
    echo '<b>The embed code...</b><br />';
    echo htmlentities($result) . '<br /><br />';
}
?>

Command Line

curl 'http://www.youtube.com/watch?v=vFMh2oeob18' | egrep '((input id="embed).*/>)' | egrep -o '(&lt;).*(/object&gt;)'