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.
Related
How YouTube Get video id from live_stream using php. I using this url
https://www.youtube.com/embed/live_stream?channel=UCmyKnNRH0wH-r8I-ceP-dsg
I try this code but return nothing
function getvideourl($chid){
$videoId = null;
// Fetch the livestream page
if($data = file_get_contents('https://www.youtube.com/embed/live_stream?channel='.$chid))
{
// Find the video ID in there
if(preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $link, $matches))
$videoId = $matches[1];
else
$videoId ="";
}
else
throw new Exception('Couldn\'t fetch data');
$video_url = "https://www.youtube.com/embed/".$videoId;
return $video_url;
}
You're using the variable $link instead of $data, try change it like this:
if(preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $data, $matches))
$videoId = substr($matches[0], 0, -2);
I'm using FQL to run this query
"SELECT post_id, actor_id, description, created_time, message, type, attachment FROM stream WHERE source_id = $page_id AND type > 0 LIMIT 0,9"
Which returns 10 items with a lot of information that isn't used and wanted some help and guidelines to help strip it down to something like
{
"image" : '...',
"text" : '...',
"username" : '...',
"userurl" : '...',
"userpic" : '...'
}
Can someone give me some tips on reformatting a JSON object?
Thanks
It works for me in a way like this:
https://graph.facebook.com/fql?q=SELECT%20aid%2C%20owner%2C%20name%2C%20object_id%20FROM%20album%20WHERE%20aid%3D%2220531316728_324257%22
Figured it out for myself, created a simple PHP class to hold the variables needed which are then added to an array.
For anyone interested here's the main bit of the code.
Class:
class Item{
public $image;
public $link;
public $text;
public $username;
public $userurl;
public $userpic;
}
Being used:
$feed = json_decode($feed);
$data = array();
foreach ($feed->data as $post){
$item = new Item;
if ($post->attachment->media){
if (isset($post->attachment->media[0]->src)){
$item->image = $post->attachment->media[0]->src;
}else if (isset($post->attachment->media[0]->photo->images[1]->src)){
$item->image = $post->attachment->media[0]->photo->images[1]->src;
}else if (isset($post->attachment->media[0]->src)){
$item->image = $post->attachment->media[0]->src;
}
$item->link = $post->attachment->media[0]->href;
}
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = $post->message;
if(preg_match($reg_exUrl, $text, $url)){
$text = preg_replace($reg_exUrl, "".$url[0]." ", $text);
}
$item->text = $text;
$puser = number_format($post->actor_id,0,'','');
$url = "https://graph.facebook.com/$puser?fields=picture,name,link&access_token=$at";
$puser = file_get_contents($url);
$puser = json_decode($puser);
$item->userpic = $puser->picture->data->url;
$item->username = $puser->name;
$item->userurl = $puser->link;
$item->platform = "facebook";
$data[] = $item;
}
$this->response($data, 200);
}
hope this helps anyone else in the same situation.
I'm using Michel Fortin's PHP Markdown for Markdown converting but i want to show images as links instead of inline. Because anyone can insert a 5MB jpg from Imgur and slow down page.
How can i change images to link-to-image?
An example of an override would look something like the follwing:
class CustomMarkdown extends Markdown
{
function _doImages_reference_callback($matches) {
$whole_match = $matches[1];
$alt_text = $matches[2];
$link_id = strtolower($matches[3]);
if ($link_id == "") {
$link_id = strtolower($alt_text); # for shortcut links like ![this][].
}
$alt_text = $this->encodeAttribute($alt_text);
if (isset($this->urls[$link_id])) {
$url = $this->encodeAttribute($this->urls[$link_id]);
$result = "$alt_text";
} else {
# If there's no such link ID, leave intact:
$result = $whole_match;
}
return $result;
}
function _doImages_inline_callback($matches) {
$whole_match = $matches[1];
$alt_text = $matches[2];
$url = $matches[3] == '' ? $matches[4] : $matches[3];
$title =& $matches[7];
$alt_text = $this->encodeAttribute($alt_text);
$url = $this->encodeAttribute($url);
return "$alt_text";
}
}
Demo: http://codepad.viper-7.com/VVa2hP
You should have a look at Parsedown. It is a more recent and, I believe, easier to extend implementation of Markdown.
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>'; ?>
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).