I am building a webpage, with search function where you can search for youtube videos and, after clicking on search those videos will be displayed on the same page. Now i want to make them playable as well so when a user search for a song, it would redirect the user to youtube however it will play the video at the same page.
here is my code for searching youtube video's:
?php
// if form submitted
} else {
// check for search keywords
// trim whitespace
// separate multiple keywords with /
if (!isset($_POST['q']) || empty($_POST['q'])) {
die ('ERROR: Please enter one or more search keywords');
}
else {
$q = $_POST['q'];
//$q = preg_replace('[[:space:]]', '/', trim($q));
}
// set max results
if (!isset($_POST['i']) || empty($_POST['i'])) {
$i = 25;
} else {
$i = $_POST['i'];
}
// generate feed URL
$feedURL = "http://gdata.youtube.com/feeds/api/videos/-/{$q}?orderby=viewCount&max-results={$i}";
//$feedURL = "http://gdata.youtube.com/feeds/api/videos/-/eminem?orderby=viewCount&max-results=10";
// read feed into SimpleXML object
$sxml = simplexml_load_file($feedURL);
//var_dump($sxml);
// get summary counts from opensearch: namespace
$counts = $sxml-> children('http://a9.com/-/spec/opensearchrss/1.0/');
//$counts = $sxml-> children('http://www.opensearch.org/Specifications/OpenSearch/1.1');
$total = $counts->totalResults;
$startOffset = $counts->startIndex;
$endOffset = ($startOffset-1) + $counts->itemsPerPage;
?>
<h1>Search results</h1>
<?php echo $total; ?> items found. Showing items
<?php echo $startOffset; ?> to <?php echo $endOffset; ?>:
<p/>
<table>
<?php
// iterate over entries in resultset
// print each entry's details
foreach ($sxml->entry as $entry) {
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
// get video player URL
$attrs = $media->group->player->attributes();
$watch = $attrs['url'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$thumbnail = $attrs['url'];
// get <yt:duration> node for video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$length = $attrs['seconds'];
// get <gd:rating> node for video ratings
$gd = $entry->children('http://schemas.google.com/g/2005');
if ($gd->rating) {
$attrs = $gd->rating->attributes();
$rating = $attrs['average'];
} else {
$rating = 0;
}
// to get the video player
$url = $watch;
parse_str( parse_url( $url, PHP_URL_QUERY ), $video_id );
}
}
?>
My question is how can I use youtube Iframe to play all the videos on my page and not going to youtube to play it.
The video ID is available in several different locations inside that XML file. You could load this part of the XML:
...<entry><id>http://gdata.youtube.com/feeds/api/videos/uelHwf8o7_U</id>...
run a regex on it to extract the video ID and then insert that ID into this code:
<?php $ajax_return = '<iframe width="560" height="315" src="http://www.youtube.com/embed/'.$youtube_ID.'" frameborder="0" allowfullscreen></iframe>'; ?>
Related
Hi I am trying to get a list of videos with the youtube api and then open that into an iframe that is on my site. The script below will retrieve a list of videos by keyword but It will only link to the page that the video is on and I would obviously like to open it into the iframe on my page. Or at least open the youtube embed in a modal. The $watch variable get the url but it comes back as https://www.youtube.com/watch?v=videoID&feature=youtube_gdata_player. This will not open in an iframe even if I put it there manually.
Is there a way to parse this. Or return it with the full embed instead of watch=tv. I also am not sure if there is a way to echo target="video-frame" in the <a> tag that is created. Is there a different variable that I need to use to get the video url and is how would I write this to echo it as for some reason when I do the server denies the page.
<?php
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/-/Keyword/';
$sxml = simplexml_load_file($feedURL);
$counts = $sxml->children('http://a9.com/-/spec/opensearchrss/1.0/');
$total = $counts->totalResults;
?>
<?php
foreach ($sxml->entry as $entry) {
$media = $entry->children('http://search.yahoo.com/mrss/');
$attrs = $media->group->player->attributes();
$watch = $attrs['url'];
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$length = $attrs['seconds'];
$gd = $entry->children('http://schemas.google.com/g/2005');
if ($gd->rating) {
$attrs = $gd->rating->attributes();
$rating = $attrs['average'];
} else {
$rating = 0;
}
echo "<li>\n";
echo "{$media->group->title}
<br/>\n";
echo sprintf("%0.2f", $length/60) . " min. | {$rating} user rating
<br/>\n";
echo "{$media->group->description}<p/>\n";
echo "<p/></li>\n";
}
?>
You can get VideoID and then put it in iframe.
Here is the code:
<?php
$string = "https://www.youtube.com/watch?v=videoID&feature=youtube_gdata_player";
$startpoint=strpos($string,'watch?v=');$startpoint=$startpoint+8;
$length=strpos($string,'&');$length = $length - $startpoint;
$videoId = substr($string,$startpoint,$length);
$ytstring = '<iframe width="560" height="315" src="https://www.youtube.com/embed/'.$videoId.'" frameborder="0" allowfullscreen></iframe>';
echo $videoId;
echo $ytstring;
?>
First of all, I would recommend to go with JSON instead of XML feed. In order to accomplish loading videos into Iframe, you'll need to use Javascript.
Here's a quick demo you can use for reference:
<?php
//YouTube json feed example:
$keyword = "basketball";
$file = file_get_contents("https://gdata.youtube.com/feeds/api/videos/-/$keyword?v=2&alt=json");
//decode into array
$decoded = json_decode($file, true);
//point the feed to 'entry' array
$entries = $decoded['feed']['entry'];
//parse through entries
if (!empty($entries)) {
for($i=0; $i<count($entries); $i++) {
$thumb = $entries[$i]['media$group']['media$thumbnail'][0]['url'];
$title = $entries[$i]['title']['$t'];
$description = $entries[$i]['media$group']['media$description']['$t'];
$video = "https://www.youtube.com/embed/".$entries[$i]['media$group']['yt$videoid']['$t']."?wmode=opaque";
$published = date('Y-m-d H:i:s', strtotime($entries[$i]['published']['$t']));
$content[]= "<img src=\"$thumb\"><br />$title<br /><small>$description<hr />$published</small>";
}
}
?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
function yt_load_video(url) {
$("iframe").attr("src",url);
return;
}
</script>
<?php if (!empty($content)) : ?>
<iframe type="text/html" src="https://www.youtube.com/embed/<?php echo $entries[0]['media$group']['yt$videoid']['$t']; ?>?wmode=opaque" frameborder="0" width="400" height="300"></iframe>
<hr />
<?php foreach($content as $thumb) : ?>
<div style="float:left; margin:4px; width:200px; height:200px; overflow:scroll"><?php echo $thumb ?></div>
<?php endforeach; ?>
<?php endif; ?>
I am trying to search youtube through the api and then save the search to a variable and then echo. Having trouble getting this to work! I have included the entire code in html. I'm not sure if it has to do with loading the youtube script library or more of a syntax error. Thanks!
<html>
<body>
<?php
$params="puppy";
function youtube_find_video($params)
{
str_replace("'", "", $params);
$q = preg_replace('/[[:space:]]/', '/', trim($params));
$q = utf8_decode(utf8_encode($q));
$replacements = array(',', '?', '!', '.');
$q = str_replace($replacements, "", $q);
$feedURL = "http://gdata.youtube.com/feeds/api/videos/-/{$q}?orderby=relevance&max-results=1";
$sxml = simplexml_load_file($feedURL);
if(!$sxml)
{
return false;
}
else{
$entry = $sxml->entry;
if(!$entry)
{
return false;
}
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
if($media)
{
// get video player URL
$attrs = $media->group->player->attributes();
$url = $attrs['url'];
if(!$url)
{
return false;
break;
}
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
$watch['id'] = $my_array_of_vars['v'];
// get video name
$watch['name'] = $media->group->title;
// get <yt:duration> node for video length[minute]
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$watch['length'] = sprintf("%0.2f", $attrs['seconds']/60);
$watch = simplexml_kurtul($watch);
return $watch;
echo $watch;
}
else
{
return false;
}
}
}
youtube_find_video();
?>
</body>
</html>
You are calling youtube_find_video() without the $params. Change the last line of PHP to:
youtube_find_video($params);
Also please give the errors you get. It's impossible to help without knowing what's wrong.
I am using PHP to grab an XML feed and display it in my website, the feed is coming from
This NewsReach Blog.
I am using some simple PHP code to get the details as show below:
$feed = new SimpleXMLElement('http://blog.newsreach.co.uk/atom.xml', null, true);
$i = 0;
foreach($feed->entry as $entry)
{
if ($i < 4)
{
$title = mysql_real_escape_string("{$entry->title}");
$summary = mysql_real_escape_string("{$entry->content}");
$summary = strip_tags($summary);
$summary = preg_replace('/\s+?(\S+)?$/', '', substr($summary, 0, 100));
$url = mysql_real_escape_string("{$entry->link[4]['href']}");
$media = $entry->children('http://search.yahoo.com/mrss/');
$attrs = $media->thumbnail[0]->attributes();
$img = $attrs['url'];
}
}
The problem that I have is that the media thumbnail tag does not exist in every blog post which causes an error to appear and stop the XML Grabber from functioning.
I have tired things like:
if ($media == 0)
{
}
else
{
$attrs = $media->thumbnail[0]->attributes();
$img = $attrs['url'];
}
or
if ($media['thumbnail'] == 0)
{
}
else
{
$attrs = $media->thumbnail[0]->attributes();
$img = $attrs['url'];
}
which I had no luck with, I was hoping someone could help me check if the XML Item existed and then process depending on that.
Thanks all
You could check if it's set and not empty:
$img = '';
if (!empty($media->thumbnail[0])) {
$attrs = $media->thumbnail[0]->attributes();
$img = $attrs['url'];
}
Remember that $media is an object, you can't access it like an array ($media['thumbnail'] should be $media->thumbnail).
I'm building a PHP program that basically grabs only image links from my twitter feed and displays them on a page, I have 3 components that I have set up that all work fine on their own.
The first component is the twitter oauth component which grabs the tweet text and creates an array, this works fine by itself.
The second is a function that processes the tweets and only returns tweets that contain image links, this as well works fine.
The program breaks down during the third section when the links are processed and an image is displayed, I had no issues running this on its own and from my attempts to trouble shoot it appears that it breaks down at the $images(); array, as that array is empty.
I'm sure I've made a silly mistake but I've been trying to find this for over a day now and can't seem to fix it. Any help would be great! Thanks guys!
code:
<?php
if ($result['socialorigin']== "twitter"){
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($result['oauthtoken'], $result['oauthsecret']);
$tweets = $twitterObj->get('/statuses/home_timeline.json',array('count'=>'200'));
$all_tweets = array();
$hosts = "lockerz|yfrog|twitpic|tumblr|mypict|ow.ly|instagr";
foreach($tweets as $tweet) {
$twtext = $tweet->text;
if(preg_match("~http://($hosts)~", $twtext)){
preg_match_all("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)#ise", $twtext, $matches, PREG_PATTERN_ORDER);
foreach($matches[0] as $key2 => $link){
array_push($all_tweets,"$link");
}
}
}
function height_compare($a1, $b1)
{
if ($a1 == $b1) {
return 0;
}
return ($a1 > $b1) ? -1 : 1;
}
foreach($all_tweets as $alltweet => $tlink){
$doc = new DOMDocument();
// Okay this is HTML is kind of screwy
// So we're going to supress errors
#$doc->loadHTMLFile($tlink);
// Get all images
$images_list = $doc->getElementsByTagName('img');
$images = array();
foreach($images_list as $image) {
// Get the src attribute
$image_source = $image->getAttribute('src');
if (substr($image_source,0,7)=="http://"){
$image_size_info = getimagesize($image_source);
$images[$image_source] = $image_size_info[1];
}
}
// Do a numeric sort on the height
uasort($images, "height_compare");
$tallest_image = array_slice($images, 0,1);
$mainimg = key($tallest_image);
echo "<img src='$mainimg' />";
}
print_r($all_tweets);
print_r($images);
}
Change the for loop where you fetch the actual images to move the images array OUTSIDE the for loop. This will prevent the loop from clearing it each time through.
$images = array();
foreach($all_tweets as $alltweet => $tlink){
$doc = new DOMDocument();
// Okay this is HTML is kind of screwy
// So we're going to supress errors
#$doc->loadHTMLFile($tlink);
// Get all images
$images_list = $doc->getElementsByTagName('img');
foreach($images_list as $image) {
// Get the src attribute
$image_source = $image->getAttribute('src');
if (substr($image_source,0,7)=="http://"){
$image_size_info = getimagesize($image_source);
$images[$image_source] = $image_size_info[1];
}
}
// Do a numeric sort on the height
uasort($images, "height_compare");
$tallest_image = array_slice($images, 0,1);
$mainimg = key($tallest_image);
echo "<img src='$mainimg' />";
}
I have started using the twitter API and would like to filter the tweets by just pulling in tweets from a specific user under a certain #hashtag. Any ideas what the corrent syntax would be, or if its possible?
This is the code I am currently using:
<?php
$username = "TwitterUsername"; // Your twitter username.
$limit = "5"; // Number of tweets to pull in.
/* These prefixes and suffixes will display before and after the entire block of tweets. */
$prefix = ""; // Prefix - some text you want displayed before all your tweets.
$suffix = ""; // Suffix - some text you want displayed after all your tweets.
$tweetprefix = ""; // Tweet Prefix - some text you want displayed before each tweet.
$tweetsuffix = "<br>"; // Tweet Suffix - some text you want displayed after each tweet.
$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=" . $limit;
function parse_feed($feed, $prefix, $tweetprefix, $tweetsuffix, $suffix) {
$feed = str_replace("<", "<", $feed);
$feed = str_replace(">", ">", $feed);
$clean = explode("<content type=\"html\">", $feed);
$amount = count($clean) - 1;
echo $prefix;
for ($i = 1; $i <= $amount; $i++) {
$cleaner = explode("</content>", $clean[$i]);
echo $tweetprefix;
echo $cleaner[0];
echo $tweetsuffix;
}
echo $suffix;
}
$twitterFeed = file_get_contents($feed);
parse_feed($twitterFeed, $prefix, $tweetprefix, $tweetsuffix, $suffix);
?>
Many thanks
You just have to change the search parameters as this (for username nycomed and hashtag copd )
http://search.twitter.com/search.atom?q=%23copd+OR+%23nycomed
i've tested this in my theme and works.You can try it even in the browser directly.
You can find more info here