Google Developer APIs

Google News Developer APIs

Google News Developer APIs allows website creators to retreive News Feeds from Google News Feeds watch out the live website.

$q = "India News";
// $q is request object based on form input submission
$page = 1;
// Increment page variable on click of next button
$ip = "<< get user ip address >>";
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
$q = urlencode($q);
$startno = $page * 8;
$url = "https://ajax.googleapis.com/ajax/services/search/
news?v=1.0&q=$q&userip=$ip&rsz=large&start=$startno";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://news.the-hindu-matrimony.com');
$body = curl_exec($ch);
curl_close($ch);
$json = json_decode($body);
for($x=0;$x<count($json->responseData->results);$x++)
{
$urljs = urldecode($json->responseData->results[$x]->url);
$contentjs = $json->responseData->results[$x]->content;
$titlejs = $json->responseData->results[$x]->title;
$signedUrljs = $json->responseData->results[$x]->signedRedirectUrl;
$publisherjs = $json->responseData->results[$x]->publisher;
$imagejs = $json->responseData->results[$x]->image->url;
$tbWidthjs = $json->responseData->results[$x]->image->tbWidth;
$tbWidthjs = $tbWidthjs."px";
$tbHeightjs = $json->responseData->results[$x]->image->tbHeight;
$tbHeightjs = $tbHeightjs."px";
$threeprofiles = $threeprofiles . "
<div class="single-blog-post" style="width: 600px;">$titlejs
$imagejs
$contentjs
$urljs
";
}

Screenshot-3Google News Live Website

Youtube Embed

Youtube Developer APIs allow web application developers to not only youtube videos and playlists but also Search Youtube Feeds , Add Videos to Playlist, Authenticate, lot more..

Embedding Youtube Playlist videos in HTML5 websites

You would need a Playlist Id and Playlist needs to be Public and Allow Embedding in its Youtube Settings.

Example if you consider this Playlist URL

https://www.youtube.com/playlist?list=PLIFVQ9iRQei9MgvahMdi4wpwkbhpNNhOV

corresponding Play list Id is

$plid = "PLIFVQ9iRQei9MgvahMdi4wpwkbhpNNhOV";

And Embed code will be

$plid = "PLIFVQ9iRQei9MgvahMdi4wpwkbhpNNhOV";
$ifrurl = "http://www.youtube.com/embed/videoseries?list=".$plid."
&autoplay=1&fs=1&iv_load_policy=3&showinfo=1&vq=hd1080&rel=0
&theme=light&origin=http://music.the-hindi-matrimony.com";
echo "<center><iframe src='$ifrurl' width='1280' height='750'
allowfullscreen='' frameborder='0'></iframe></center> ";

Youtube Playlist

Embedding Youtube Single Video  in HTML5 websites

You would need a Video Id and Video needs to be Public and Allow Embedding in its Youtube Settings.

Example if you consider this Video URL

https://www.youtube.com/watch?v=8ZFvU8b_IDw

And Embed code will be

// Get video Id parameter of "v="
 $vid = "8ZFvU8b_IDw";
 echo "<center><iframe id='ytplayer' type='text/html'
 width='1280' height='750'
 src='http://www.youtube.com/embed/$vid?autoplay=1
 &fs=1&iv_load_policy=3
 &showinfo=1&theme=light&vq=hd1080&rel=0
 &origin=http://music.the-hindi-matrimony.com'
 allowfullscreen='' frameborder='0'/></center> ";

Screenshot-7

Youtube developer API s

Its interesting to develop code using Google Developer API’s , you can use Java Script, Java, PHP other programming languages, to build web interface around these APIs . first step would be to register your website and get Developer Key

Sign In and create a New project here https://console.developers.google.com/

Once a project has been created Select APIs that you would like to use

Screenshot-4

Select Credentials and copy paste the API codes

Screenshot-5

Youtube Search Query

    //$q = "Md Rafi"; Your Search Term
    //$maxResults = 12; No of Results to be returned
    function youtubesearch($q, $maxResults)
    {
        if ($q != "" && $maxResults != "")
        {
            $headlabel = "Youtube Search Results ! ";
            $DEVELOPER_KEY = 'Your Developer Key';
            $client = new Google_Client();
            $client->setDeveloperKey($DEVELOPER_KEY);
            $youtube = new Google_Service_YouTube($client);
            try
            {
                $searchResponse = $youtube->search->listSearch('id,snippet', array( 'q' => $q, 'maxResults' => $maxResults, ));
                $videos = '';
                $channels = '';
                $playlists = '';

                        foreach ($searchResponse['items'] as $searchResult)
                        {
                                switch ($searchResult['id']['kind'])
                                {
                                    //==================== Just Videos ====================================
                                    case 'youtube#video':
                                        $videos .= sprintf('<li>%s (%s)</li>',$searchResult['snippet']['title'], $searchResult['id']['videoId']);
                                        $titleyt = $searchResult['snippet']['title'];
                                        $str = "http://img.youtube.com/vi/".$searchResult['id']['videoId']."/hqdefault.jpg";
                                        $vid = $searchResult['id']['videoId'];

                                            // ----------------- UI -----------------
                                            echo "<div class='col-sm-2'> <div class='product-image-wrapper'> <div class='single-products'>
                                           <div class='productinfo text-center'>";
                                            echo " <img src='$str'/><br/> ";
                                            echo "<input type='button' class='btn btn-default add-to-cart'
                                            name='$vid' value='$vid' onclick='showUser(this.value)' /><br/>  ";
                                            echo "</div> </div> </div> </div>";
                                            $mostviewed = $mostviewed ."
                                            <div class='col-sm-2'>
                                            <div class='product-image-wrapper'>
                                            <div class='single-products'>
                                            <div class='productinfo text-center'>
                                            <img src='$str' alt='' height='100%'  width='100%' />
                                            <h4 class='title text-center' style='color: #FE980F;'>   Video      </h4>
                                            Vd: <input type='button' class='btn btn-default add-to-cart'
                                            name='$vid' value='$vid' onclick='showUser(this.value)' />
                                            </div>
                                            </div>
                                            </div>
                                            </div>";
                                            // ----------------- UI -----------------
                                      break;

                                      //==================== Just Playlists ====================================
                                      case 'youtube#playlist':
                                            $playlists .= sprintf('<li>%s (%s)</li>',$searchResult['snippet']['title'], $searchResult['id']['playlistId']);
                                            $titleyt2 = $searchResult['snippet']['title'];
                                            $str2 = "http://img.youtube.com/vi/".$searchResult['id']['playlistId']."/hqdefault.jpg";
                                            $vid2 = $searchResult['id']['playlistId'];
                                            // ----------------- UI -----------------
                                            echo "<div class='col-sm-2'> <div class='product-image-wrapper'>
                                            <div class='single-products'> <div class='productinfo text-center'>";
                                            echo " <img src='$str2'/><br/> ";
                                            echo "<input type='button' class='btn btn-default add-to-cart' name='$vid2' value='$vid2'
                                            onclick='showUser(this.value)' /><br/>  ";
                                            echo "</div> </div> </div> </div>";
                                            $mostviewed = $mostviewed ."
                                            <div class='col-sm-2'>
                                            <div class='product-image-wrapper'>
                                            <div class='single-products'>
                                            <div class='productinfo text-center'>
                                            <img src='$str2' alt='' height='100%'  width='100%' />
                                            <h4 class='title text-center' style='color: #FE980F;'>   Playlist      </h4>
                                            Pl: <input type='button' class='btn btn-default add-to-cart' name='$vid2' value='$vid2'
                                            onclick='showUser(this.value)' />
                                            </div>
                                            </div>
                                            </div>
                                            </div>";
                                            // ----------------- UI -----------------
                                       break;
                                }
                          }

                    }
                    catch (Google_ServiceException $e)
                    {
                    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
                    }
                        catch (Google_Exception $e)
                        {
                        $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
                        htmlspecialchars($e->getMessage()));
                        }

                        }
                        $mostviewed = $mostviewed ." </div> ";

    }

Youtube Video

Screenshot-8

Adding videos to Playlist

Authorize User

Screenshot-9

Accept consent

Screenshot-10

Create Token & Execute API

Screenshot-11

View Updated Playlist

Screenshot-12

<?php

// Call set_include_path() as needed to point to your client library.
/*
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
*/
require_once 'vendor/google/apiclient/src/Google/Client.php';
require_once 'vendor/google/apiclient/src/Google/Service/YouTube.php';

session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google Developers Console <https://console.developers.google.com/>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'your client id ';
$OAUTH2_CLIENT_SECRET = 'your client secret';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] .
$_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try {
    // This code creates a new, private playlist in the authorized user's
    // channel and adds a video to the playlist.

    // 1. Create the snippet for the playlist. Set its title and description.
    $playlistSnippet = new Google_Service_YouTube_PlaylistSnippet();
    $playlistSnippet->setTitle('Test Playlist  ' . date("Y-m-d H:i:s"));
    $playlistSnippet->setDescription('A private playlist created with the YouTube API v3');

    // 2. Define the playlist's status.
    $playlistStatus = new Google_Service_YouTube_PlaylistStatus();
    $playlistStatus->setPrivacyStatus('public'); // public or private

    // 3. Define a playlist resource and associate the snippet and status
    // defined above with that resource.
    $youTubePlaylist = new Google_Service_YouTube_Playlist();
    $youTubePlaylist->setSnippet($playlistSnippet);
    $youTubePlaylist->setStatus($playlistStatus);

    // 4. Call the playlists.insert method to create the playlist. The API
    // response will contain information about the new playlist.
    //$playlistResponse = $youtube->playlists->insert('snippet,status', $youTubePlaylist, array());
    //$playlistId = $playlistResponse['id'];
    // Documentaries Playlist
    $playlistId = "your playlist id";
    // 5. Add a video to the playlist. First, define the resource being added
    // to the playlist by setting its video ID and kind.
    $resourceId = new Google_Service_YouTube_ResourceId();
    $resourceId->setVideoId('your video id');
    $resourceId->setKind('youtube#video');

    // Then define a snippet for the playlist item. Set the playlist item's
    // title if you want to display a different value than the title of the
    // video being added. Add the resource ID and the playlist ID retrieved
    // in step 4 to the snippet as well.
    $playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
    $playlistItemSnippet->setTitle('First video in the test playlist');
    $playlistItemSnippet->setPlaylistId($playlistId);
    $playlistItemSnippet->setResourceId($resourceId);

    // Finally, create a playlistItem resource and add the snippet to the
    // resource, then call the playlistItems.insert method to add the playlist
    // item.
    $playlistItem = new Google_Service_YouTube_PlaylistItem();
    $playlistItem->setSnippet($playlistItemSnippet);
    $playlistItemResponse = $youtube->playlistItems->insert(
        'snippet,contentDetails', $playlistItem, array());

    $htmlBody .= "<h3>New Playlist</h3><ul>";
    $htmlBody .= sprintf('<li>%s (%s)</li>',
        $playlistResponse['snippet']['title'],
        $playlistResponse['id']);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>New PlaylistItem</h3><ul>";
    $htmlBody .= sprintf('<li>%s (%s)</li>',
        $playlistItemResponse['snippet']['title'],
        $playlistItemResponse['id']);
    $htmlBody .= '</ul>';

  } catch (Google_ServiceException $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
        htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
        htmlspecialchars($e->getMessage()));
  }

  $_SESSION['token'] = $client->getAccessToken();
} else {
  // If the user hasn't authorized the app, initiate the OAuth flow
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
}
?>

<!doctype html>
<html>
<head>
<title>New Playlist</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

Vimeo APIs

To Iframe Vimeo Videos , first thing i prefer to do is grab the RSS Feed , Parse it , Get the Video Id and Iframe the Video

Step 1 Get RSS Feeds,

From Vimeo.com website the RSS Feeds look like this

http://vimeo.com/staff/likes/rss
http://vimeo.com/channels/staffpicks/videos/rss
http://vimeo.com/channels/documentaryfilm/videos/rss

Step 2 Decode the RSS Feed to Get Video Id

function vimeoFeeds($url)
    {

        $mostviewed = " ".$this->vimeolist()." ";
        $mostviewed = $mostviewed ."<div class='features_items'>     ";
        //================ Rss Code ================================
        $rss = new DOMDocument();
        //$url = "http://vimeo.com/staff/likes/rss";
        $rss->load($url);
        $feed = array();
        foreach ($rss->getElementsByTagName('item') as $node)
        {
            $item = array
            (
                'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                'guid' => $node->getElementsByTagName('guid')->item(0)->nodeValue,
                'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
                'pubDate' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
                'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                'url' => $node->getElementsByTagName('url')->item(0)->nodeValue,
                'id' => $node->getElementsByTagName('id')->item(0)->nodeValue,
                'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
                'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
                'image' => $node->getElementsByTagName('thumbnail')->item(0) ?
$node->getElementsByTagName('thumbnail')->item(0)->getAttribute('url') : '',
                'imageht' => $node->getElementsByTagName('thumbnail')->item(0) ?
$node->getElementsByTagName('thumbnail')->item(0)->getAttribute('height') : '',
                'imagewd' => $node->getElementsByTagName('thumbnail')->item(0) ?
$node->getElementsByTagName('thumbnail')->item(0)->getAttribute('width') : '',
            );
            array_push($feed, $item);
        } 

        $limit = 24;
        for($x=0;$x<$limit;$x++)
        {
            $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
            $link = $feed[$x]['link'];
            $description = $feed[$x]['desc'];
            $pubDate = $feed[$x]['pubDate'];
            $title = $feed[$x]['title'];
            $url = $feed[$x]['url'];
            $id = $feed[$x]['id'];
            $image = $feed[$x]['image'];
            $imageht = $feed[$x]['imageht'];
            $imagewd = $feed[$x]['imagewd'];
            $guid = $feed[$x]['guid'];
            $guid  = explode(":", $guid );
            $vid = $guid[2];
            $vid = str_replace('clip', '', $vid);
            if($vid != "")
            {
                $mostviewed = $mostviewed ." <div class='col-sm-2'>
                <div class='product-image-wrapper'>
                <div class='single-products'>
                <div class='productinfo text-center'>
                <h4> $title </h4>
                <img src='$image' height='$imageht' width='$imagewd' >
                <input type='button' class='btn btn-default add-to-cart'
name='$vid' value='$vid' onclick='showUser(this.value)' />
                </div>
                </div>
                </div>
                </div>  ";
            }
        }
        //================ Rss Code ================================
        $mostviewed = $mostviewed ." </div>  ";
        return $mostviewed;
    }

Vimeo IFraming allows us to Embed rich Vimeo Feeds into our Web site

Step 3 Onclick of a button use PHP Ajax to Embed Video

$vid =  $_GET['q'] ;
echo "<center>
<iframe src='//player.vimeo.com/video/$vid?autoplay=1&badge=1&color=#FFFFFF'
width='800px' height='600px' frameborder='0' webkitallowfullscreen
mozallowfullscreen allowfullscreen>
</iframe>
 </center> ";

Screenshot-13

Vimeo Feed Website

Twitter Authenticate and Hashtag search

You can authenticate to twitter , use the key and do a hash tag search , here is my simple helper class MyTwitt.php

<?php
class TwitHome
{
    // connection is post authorized connection info
    // q is hashtag search query , example #cricket
    function searchTweets($connection, $q)
    {
            $max_id = "";
            foreach (range(1, 10) as $i)
            { // up to 10 result pages
            
                $query = array(
                    "q" => "$q since:2014-01-01 until:2014-12-31", // Change here
                    "count" => 20,
                    "result_type" => "recent",
                    "max_id" => $max_id,
                );
        
                $results = $connection->get('search/tweets', $query); 
                foreach ($results->statuses as $result)
                {                    
                    $max_id = $result->id_str; 
// Set max_id for the next search result page                   
                    $user = $result->user->screen_name;
                    $str = $result->text;
                    // Replace text link with hyper links
$new_string = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]"
,"<a href=\"\\0\" target='_new'>\\0</a>", $str);
 echo "<div class='single-blog-post' style='width:600px;'>
<b>$user</b> $new_string  </div>";
                     
                }
            }
    }
    
}
?>

The Main PHP file that would call the the search function is index.php

// If twitter button is clicked in search
if($submit == "Twitter")
	{
	    // Handle Twitter
	    include ('twitter/MyTwit.php');
	    require_once('twitter/twitteroauth/twitteroauth.php');
	    require_once('twitter/config.php');
	    
	    // Remove Hash if exists example #Cricket will be Cricket
	    $q = str_replace('#','',$q);
	    
	    // Add Hash after removal before sending to twitter
            // Example India will be #India
	    $q = "#".$q;
	    $ObjTwitHome = new TwitHome;
	    /* If access tokens are not available redirect to connect page. */
	    if (empty($_SESSION['access_token']) || 
empty($_SESSION['access_token']['oauth_token']) || 
empty($_SESSION['access_token']['oauth_token_secret']))
	    {
	        header('Location: twitter/clearsessions.php');
	    }
	    /* Get user access tokens out of the session. */
	    $access_token = $_SESSION['access_token'];
	    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, 
$access_token['oauth_token'], $access_token['oauth_token_secret']);
	    $content = $connection->get('account/verify_credentials');
	    $account = $connection->get('account/verify_credentials');
	    $msg = "This is Twitter API test msg at ".date(DATE_RFC822);
            // If no search tag , then initiate
	    if($q == "")
	    {
	        $q = "#IndianNews";
	    } 
             // call search function
             $ObjTwitHome->searchTweets($connection, $q); 
	}

Screenshot-18

Google News or Twitter search