I'm not sure when, but at some point my YouTube searching method stopped working, it has worked for years but both the API and the preferred method of displaying embedded video has changed. I've looked at the official Google docs and I have the option of using Zend or the currently in development Version 3 of the Google API, these are a lot larger codebases than what I was currently using.
I've tried debugging my code and may eventually get it working again, should I just scrap it and integrate the more official PHP codebase into my project. This was is where my method sits, it finds data, but I don't seem to display any videos...
public function embeddableVideoClipFor($searchString)
{
// Previous experience revealed that video search is not perfect, but we're just going to giver and create an embedded player with the
// top result or return NULL
// I used this as a guide to build my embedded player http://code.google.com/apis/youtube/youtube_player_demo.html
$embeddableVideoClipHTML = NULL;
// Further details on searching YouTube http://www.ibm.com/developerworks/xml/library/x-youtubeapi/
// This was working well for over two years but now I'm getting no videos, I may have been throttled or more likely the API has changed...
// Before switching to Zend or going to switch to version 3.0 of Google/YouTube API I should try and debug...
$vq = $searchString;
$vq = preg_replace('/[[:space:]]+/', ' ', trim($vq));
$vq = urlencode($vq);
$feedURL = 'http://gdata.youtube.com/feeds/api/videos?q=' . $vq . '&safeSearch=none&orderby=viewCount&v=2'; // Added version two tag...
print_r($feedURL);
// read feed into SimpleXML object
try
{
$youTubeXML = simplexml_load_file($feedURL);
}
catch(Exception $e)
{
// This rarely throws an error, but when it does, I just want to pretend I can't find a video clip
$youTubeXML = NULL;
}
print("<pre>");
print_r($youTubeXML);
print("</pre>");
if(($youTubeXML != NULL) && ( ! empty($youTubeXML->entry->link[0]['href'])))
{
$videoLink = $youTubeXML->entry->link[0]['href']; // This is not enough, I need to trim the beginning and end off this to just get the video code
$trimedURL = str_replace('http://www.youtube.com/watch?v=', '' , $videoLink);
$videoCode = str_replace('&feature=youtube_gdata', '', $trimedURL);
// $embeddableVideoClipHTML = '<object style="height: 390px; width: 640px"><param name="movie" value="http://www.youtube.com/v/' . $videoCode . '"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed src="http://www.youtube.com/v/' . $videoCode . '?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="390"></object>';
// $embeddableVideoClipHTML = '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/' . $videoCode . '"frameborder="0" allowfullscreen>';
// Version 3
$embeddableVideoClipHTML = '<object width="640" height="360"><param name="movie" value="https://www.youtube.com/v/' . $videoCode . '?version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed src="https://www.youtube.com/v/' . $videoCode . '?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="360"></embed></object>';
}
return $embeddableVideoClipHTML;
}
I'm not sure why, because I did try it, but switching to the iFrame, ie this line of code:
// $embeddableVideoClipHTML = '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/' . $videoCode . '"frameborder="0" allowfullscreen>';
Works now, but I still wonder if I should jump through hoops to use one of the more official PHP frameworks, I really only use this one method to access the Google/YouTube api, it isn't a big part of my mashup, but I like it for movie trailers and song lyric quotations.
Related
i have a posting feature on my site that can embed links and youtube videos. the problem is, that the two clash together, and the youtube iframe ends up being a 404 page on my site. my codes for the youtube videos and links are below, but im not sure how to stop them from combining and ruining it.
by combining, i mean this http://www.youtube.com/watch?v=VhqiT2nWCVU turns to
<iframe src="http://www.youtube.com/watch?v=VhqiT2nWCVU">
which then turns into
<iframe src="">
sorry if i am unclear in any way. my codes are below.
function youtube($string)
{
return preg_replace(
'#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i',
'<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/$4?rel=0" frameborder="0" allowfullscreen></iframe>',
$string
);
}
$posted = youtube($posted);
$rexProtocol = '(https?://)?';
$rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]+?)?';
// Solution 1:
function callback($match)
{
// Prepend http:// if no protocol specified
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
return '<a href="' . $completeUrl . '">'
. $match[2] . $match[3] . $match[4] . '</a>';
}
$posted = preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",
'callback', $posted);
A popular solution to this problem is to use placeholders. On your first pass you turn all YouTube links into a placeholder, for example:
{{youtube:VhqiT2nWCVU}}
After that you run your normal link converter. And at the end your run yet another regex to turn all your palceholders into youtube embeds.
I've recently registered my site at an affiliate network which lets blogs write about me for a fixed price. But I'm having some difficulties adding the code properly.
Here's the code that I'm supposed to add:
<iframe src="http://track.domain.com/?trackID=[CookieID]&orderValue=[orderValue]&orderID=[orderID]&programID=319" scrolling="no" frameborder="0" width="1" height="1"></iframe>
So here's the code I tried to add in the success-page, which is where the code is supposed to be sent to the affiliate network (if the page is accessed through a given link). Notice that I'm trying to send a test order just to make sure it's added to my profile.
<?php
class ControllerCheckoutSuccess extends Controller {
public function index() {
$adrecordPixel = '<iframe src="http://track.adrecord.com/?trackID=' . $_COOKIE['trackID'] . '&orderValue=555555&orderID=5555555&programID=319&test=' . $this->session->data['order_id'] . '" scrolling="no" frameborder="0" width="1" height="1"></iframe>';
And
if ($this->customer->isLogged()) {
$this->data['text_message'] = sprintf($this->language->get('text_customer'), $this->url->link('account/account', '', 'SSL'), $this->url->link('account/order', '', 'SSL'), $this->url->link('account/download', '', 'SSL'), $this->url->link('information/contact'));
$this->data['text_message'] = $adrecordPixel;
But it doesn't work :(
Anyone has any idea on how I can do this?
I will refresh each 5 minutes to check for answers and I will reply asap. If anyone wants to know the URL just ask.
Thanks in advance
Why are you writing over $text_message variable with this line:
$this->data['text_message'] = $adrecordPixel;
Just prepare the html in its own variable in the controller index() function and pass it:
$this->data['pixel'] = '<iframe src="http://track.adrecord.com/?trackID=' . $_COOKIE['trackID'] . '&orderValue=555555&orderID=5555555&programID=319&test=' . $this->session->data['order_id'] . '" scrolling="no" frameborder="0" width="1" height="1"></iframe>';
Then echo $pixel in your view wherever.
I am currently adapted a code to my website's use but now I would like to change some of its format but it has been a harder task than expected. My code right now is displaying the latest video. But my goal at the moment is to have the code display the videos *thumbnail pic, *video description and *total views. Below is my code, If you think there is a better way to approach this then I am open for suggestions:
<?
error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/users/USERNAME/uploads?max-results=20';
$sxml = simplexml_load_file($feedURL);
$i = 0;
foreach ($sxml->entry as $entry) {
$media = $entry->children('media', true);
$url = (string)$media->group->player->attributes()->url;
$index = strrpos($url, "&");
$url = substr($url, 0, $index);
$index = strrpos($url, "watch");
$url = substr($url, 0, $index) . "v/" . substr($url, $index + 8, strlen($url) - ($index + 8));
echo '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="400" height="250" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="' . $url . '" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="400" height="250" src="' . $url . '" allowscriptaccess="always" allowfullscreen="true"></embed></object>';
break;
}
?>
To build on Chris Willenbrock's work, in order to simplify the code a little and save yourself some overhead (an extra entries 20-$count across the wire, extra explode on 20-$count entries that won't be displayed anyway):
//SETTINGS
$channel_name = 'mychannelname';//Be sure to change this to your channel
$count = 8;//# of videos you want to show (MAX = 20)
$em_width = 420;//width of embedded player
$em_height = 315;//height of embedded player
$wrap_class = 'video';//class name for the div wrapper
//The output...
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/$channel_name/uploads?max-results=$count");
foreach ($sxml->entry as $entry) {
$vidKey = substr(strrchr($entry->id,'/'),1);
echo "
<div class=\"$wrap_class\">
<iframe width=\"$em_width\" height=\"$em_height\" src=\"http://www.youtube.com/embed/$vidKey\" frameborder=\"0\" allowfullscreen></iframe>
</div>
";
}
I don't enjoy working with XML and avoid it where I can, so here is another option that uses JSON. Also, note that by switching to v2 of the API here we get much cleaner access to the video key, as well as the other meta-data that the original poster was asking for:
//The output...
$api_v2 = "http://gdata.youtube.com/feeds/api/users/$channel_name/uploads?max-results=$count&v=2";
foreach (json_decode(file_get_contents("$api_v2&alt=json"))->feed->entry as $entry) {
// meta information
$title = $entry->title->{'$t'};
$description = $entry->{'media$group'}->{'media$description'}->{'$t'};
$views = $entry->{'yt$statistics'}->viewCount;
$thumbnails = $entry->{'media$group'}->{'media$thumbnail'};
// few different thumbnail image choice here:
// 0 => default image, low res - "default"
// 1 => default image, medium res - "mqdefault"
// 2 => default image, higher res - "hqdefault"
// 3 => first frame of vid, low res - "start"
// 4 => middle frame, low res - "middle"
// 5 => last frame, low res - "end"
$thumb_img = $thumbnails[1]; // I'll go with default, medium res
echo "
<!-- meta information output - format to taste -->
<div>
<img src='$thumb_img->url' style='float: left; margin-right: 10px;' width='$thumb_img->width' height='$thumb_img->height' alt='{$thumb_img->{'yt$name'}}'>
<b>Title:</b> $title<br><br>
<b>Description:</b> $description<br><br>
<b>Views:</b> $views
<br style='clear: left;'>
</div>
<div class=\"$wrap_class\">
<iframe width=\"$em_width\" height=\"$em_height\" src=\"{$entry->content->src}\" frameborder=\"0\" allowfullscreen></iframe>
</div>
";
}
Add
var_dump($entry);exit;
at the first line inside the foreach code, then take a look at the output and search for your thumbnail images. Then you have to follow the path like it was done with the URL ($entry->children(..) and $media->path->to->thumbnail)
Youtube has updated their embed methods and api output, so I took the opportunity to update the script. You can probably just move all of the settings into the core part of the script, but I figured I'd pull it out to make it easier to follow. Hope this helps:
//SETTINGS
$channel_name = 'mychannelname';//Be sure to change this to your channel
$count = 8;//# of videos you want to show (MAX = 20)
$em_width = 420;//width of embeded player
$em_height = 315;//height of embeded player
$wrap_class = 'video';//class name for the div wrapper
//The output...
error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/users/'.$channel_name.'/uploads?max-results=20';
$sxml = simplexml_load_file($feedURL);
$i = 1;
foreach ($sxml->entry as $entry) {
$vidUrl = explode("/", $entry->id);
$vidKey = $vidUrl[6];
if ($i <= $count ) :
echo '
<div class="'.$wrap_class.'">
<iframe width="'.$em_width.'" height="'.$em_height.'" src="http://www.youtube.com/embed/'.$vidKey.'" frameborder="0" allowfullscreen></iframe>
</div>
';
endif;
$i++;
}
i have php function which generate youtube code to display video but auto play is not working properly
function get_youtube_embed($youtube_video_id = 0, $auto = 0) {
$embed_code = "";
if ($auto == 1) {
$embed_code = '<iframe width="589" height="342" src="http://www.youtube.com/embed/' . $youtube_video_id . '?autoplay=1" frameborder="0" allowfullscreen></iframe>';
}
else {
$embed_code = '<iframe width="589" height="342" src="http://www.youtube.com/embed/' . $youtube_video_id . '" frameborder="0" allowfullscreen></iframe>';
}
return $embed_code;
}
Thanks
Your code is alright, try doing it by hand, without Javascript. Most likely that the way to set autoplay is wrong in your code.
It appears that the autoplay does not always work in the newer
At the bottom of the embed option section on the youtube site, there is a checkbox allowing you to use the old code. Use this as your base.
Your code should look something like this:
$embed_code = '<object width="420" height="345"><param name="movie" value="http://www.youtube.com/v/' . $youtube_video_id . '?version=3&hl=en_US&rel=0&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' . $youtube_video_id . '?version=3&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" width="420" height="345" allowscriptaccess="always" allowfullscreen="true"></embed></object>';
see: http://www.google.com/support/youtube/bin/answer.py?answer=171780&expand=UseOldEmbedCode#oldcode
This is what I've got so far:
<?php
$content = "word1 http://www.youtube.com/watch?v=yqfKe-67foQ&feature=related word2 http://www.youtube.com/watch?v=2vq7gDEn99Y&feature=related word3 http://www.youtube.com/watch?v=nW5HxgMYRto\nhttp://www.youtube.com/watch?v=8Uc2lpH0iZ0&feature=fvhl";
$pattern = '/http:\/\/www\.youtube\.com\/watch\?(.*)v=([a-zA-Z0-9_\-]+)(\S*)/i';
$replace = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/$2&hl=en_US&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$2&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
$content = preg_replace($pattern, $replace, $content);
echo $content;
?>
I honestly have no idea why it doesn't work. Some help would be appreciated. Thanks.
You just have to make * non-greedy:
http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*)
See "Watch out for greediness".
Try this simple function for URL replacement
function youtube($string)
{
return preg_replace(
'#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i',
'<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/$4" frameborder="0" allowfullscreen></iframe>',
$string
);
}
echo youtube('http://www.youtube.com/watch?v=VWsjWCt1PsQ');
echo youtube('http://youtube.com/watch?v=VWsjWCt1PsQ');
echo youtube('http://youtube.com/v/VWsjWCt1PsQ');
echo youtube('http://www.youtube.com/v/VWsjWCt1PsQ');
I would just create a string with a configured embed code. Link attribute could be #LINK#, width="#WIDTH#". Than replace all parameters with your own value. It could be much more comfortable to use. Or you can simply use a youtube embed code generator for that.