Have you ever seen latest twitter posts or youtube videos on websites and wondered how this is done? This blog gives you the code so that you are able to include your latest social media feeds using PHP. The code used is built upon a great article by James Bavington & Rob Kent at the creare group. Whilst some of the code is the same I have built upon their solution to make it more reusuable and also include Youtube functionality. Nevertheless, I would recommend checking out their article (once you have dessiminated the information presented here).
For an indepth review of the code please watch the video above. If you do have any comments regarding this please leave them in the comments box at the bottom of the blog.
Our getLatestYoutube method returns an array containing the url and date of each result that you have requested. You can use the array to show your latest videos in any format that you wish.
include('SocialMedia.php');
$socialMedia = new SocialMedia();
$videos = $socialMedia->getLatestYoutube("afxdesignltd",1);
foreach($videos as $video) {
echo "<iframe width='262' height='147' src='http://www.youtube.com/embed/{$video['url']}?rel=0?version=3&controls=0&feature=player_embedded&rel=0' frameborder='0' allowfullscreen></iframe>";
echo "<br />Posted {$video['date']}<br /><br />";
}
The getLatestTweet method is very similar to the youtube equivalent and returns an array containing your tweet and the date it was posted.
$tweets = $socialMedia->getLatestTweet("afxdesign",1);
foreach($tweets as $tweet) {
echo $tweet['tweet']."<br />";
echo $tweet['date']."<br /><br />";
}
Using the social media class you are able to grab your latest posts on Youtube and Twitter with ease. The class includes cacheing to ensure that you are not suspected as overloading the server.
<?php
class SocialMedia {
/*********************************************
* function getXML($user, $file_name)
* Returns cached version of file or grabs and caches a new version
* if there is not a current cached version [or] the cached version is
* over an hour old.
*
* @param string $url Location of file to grab
* @param string $filename File to save cached version
* @return string $xmlstring File contents or empty
***********************************************/
function getXML($url,$filename) {
$xmlstring = false;
if(file_exists($filename)) {
if(strtotime('+ 1 hour',filemtime($filename)) > strtotime("now")) $xmlstring = file_get_contents($filename);
}
if($xmlstring === false) {
$xmlstring = file_get_contents($url);
$fh = fopen($filename,'w');
fwrite($fh,$xmlstring);
fclose($fh);
}
return $xmlstring;
}
/*********************************************
* function getTimeMessage($datetime)
* Takes a date and returns an easy to read format based on how
* long ago it was.
*
* @param string $datetime Date that you would like to convert
* @return string $timemessage Date in easy to read format
***********************************************/
function getTimeMessage($datetime) {
$timeago = (time() - strtotime($datetime));
$thehours = floor($timeago/3600);
$theminutes = floor($timeago/60);
$thedays = floor($timeago/86400);
if($theminutes < 60){
if($theminutes < 1){
$timemessage = "Less than 1 minute ago";
} else if($theminutes == 1) {
$timemessage = $theminutes." minute ago.";
} else {
$timemessage = $theminutes." minutes ago.";
}
} else if($theminutes > 60 && $thedays < 1){
if($thehours == 1){
$timemessage = $thehours." hour ago.";
} else {
$timemessage = $thehours." hours ago.";
}
} else {
if($thedays == 1){
$timemessage = $thedays." day ago.";
} else {
$timemessage = $thedays." days ago.";
}
}
return $timemessage;
}
/*********************************************
* function changeLink($string, $tags=false, $nofollow, $target)
* Returns formated link based on user inputs.
*
* @param string $link HTML containing link
* @param boolean $tags If true then turns to plain text
* @param boolean $nofollow If true then adds rel 'nofollow' attribute
* @param boolean $target If true then adds target '_blank' attribute
* @return string $link Returns formatted link
**********************************************/
function changeLink($link, $tags=false, $nofollow=false, $target=false){
if($tags) {
$link = strip_tags($link);
} else {
if($target) {
$link = str_replace("<a", "<a target=\"_blank\"", $link);
}
if($nofollow) {
$link = str_replace("<a", "<a rel=\"nofollow\"", $link);
}
}
return $link;
}
/*********************************************
* function getLatestYouTube($user, $results = 10)
* Grabs youtube videos and date based on parameters passed.
*
* @param string $user Youtube user id
* @param integer $results Total results
* @return array $videos Array containing 'date' and 'url' for each row
**********************************************/
function getLatestYoutube($user,$results = 10) {
$rssfeed = "http://gdata.youtube.com/feeds/base/users/{$user}/uploads?orderby=updated&alt=rss&client=ytapi-youtube-rss-redirect&v=2&max-results={$results}";
$xmlstring = $this->getXML($rssfeed,'youtube.xml');
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xmlstring);
$x = $xmlDoc->getElementsByTagName("item"); // get all entries
$videos = array();
foreach($x as $item){
$tmpvideo=array();
if($item->childNodes->length) {
foreach($item->childNodes as $i) {
$tmpvideo[$i->nodeName] = $i->nodeValue;
}
}
$timemessage = $this->getTimeMessage($tmpvideo['pubDate']);
$matches = array();
preg_match( "/.*?v=(.*?)&/" , $tmpvideo['link'], $matches );
$videos[] = array('date'=>$timemessage,'url'=>$matches[1]);
}
return $videos;
}
/*********************************************
* function getLatestTweet($user,$results, $tags=false, $nofollow=true, $target=true)
* Grabs tweets and date based on parameters passed.
*
* @param string $user Twitter user id
* @param integer $results Total results
* @param boolean $tags If false links are not clickable
* @param boolean $nofollow If true then adds rel 'nofollow' attribute
* @param boolean $target If true then adds target '_blank' attribute
* @return array $tweetarray Array containing 'date' and 'tweet' for each row
**********************************************/
function getLatestTweet($user,$results, $tags=false, $nofollow=true, $target=true){
$rssfeed = "http://search.twitter.com/search.atom?q=from:{$user}&rpp={$results}";
$xmlstring = $this->getXML($rssfeed,'twitter.xml');
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xmlstring);
$x = $xmlDoc->getElementsByTagName("entry");
$tweets = array();
foreach($x as $item){
$tweet = array();
if($item->childNodes->length) {
foreach($item->childNodes as $i){
$tweet[$i->nodeName] = $i->nodeValue;
}
}
$tweets[] = $tweet;
}
$tweetarray = array();
foreach($tweets as $tweettag){
$tweetdate = $tweettag["published"];
$tweet = $tweettag["content"];
$timedate = explode("T",$tweetdate);
$date = $timedate[0];
$time = substr($timedate[1],0, -1);
$tweettime = $date." ".$time;
$timemessage = $this->getTimeMessage($tweettime);
$tweet = $this->changeLink($tweet, $tags, $nofollow, $target);
$tweetarray[] = array('tweet'=>$tweet,'date'=>$timemessage);
}
return $tweetarray;
}
}
?>