Monday, November 9, 2015

Working with Twitter API

In this session we are going to learn how to use Twitter API to get public tweets using PHP and javaScript.

first I have found 2 PHP files which help you to work with API. From the below link you can download those files.

https://codeload.github.com/abraham/twitteroauth/zip/0.2.0-beta2

Inside the zip file you have downloaded you can find 2 PHP files called,
  • OAuth.php
  • twitteroauth.php


First you have to copy those 2 files to a folder before start any of coding. Actually we don't even have to do a single change in those files thanks to abraham's (https://github.com/abraham) twitteroauth.

After that just create a new PHP file inside the same folder and name it as index.php.

This where we are going to do some coding.

first we have to first call the twitteroauth.php file using following code.

<?php include "twitteroauth.php";?>


Then we have to connect our twitter app (which was created using https://apps.twitter.com/) to get data.

<?php
$consumer = "";
$consumersecret = "";
$accesstoken = "";
$accesstokensecret = "";

$twitter = new TwitterOAuth($consumer,$consumersecret,$accesstoken,$accesstokensecret);

$tweets = $twitter->get('https://api.twitter.com/1.1/search/tweets.json?q=twd');


?>


You can find your consumer, consumersecret, accesstoken and accesstokensecret keys from https://apps.twitter.com/ .

And also you have to get a search method from https://dev.twitter.com/rest/tools/console and put it in $tweet.

The rest of the code is simple. You just have to do some html stuff to arrange the tweets in away that you can understand.

<html>
<head>
<meta charset="UTF-8"/>
<title>Twitter API</title>
</head>

<body>
<form action="" method="post">
<label>Search : <input type="text" name="keyword"/></label>
</form>

<?php
if (isset($_POST['keyword'])){
$tweets = $twitter->get('https://api.twitter.com/1.1/search/tweets.json?q='.$_POST['keyword'].'&lang=en&result_type=recent&count=50');

foreach($tweets->statuses as $tweet){

echo 'Text - '.$tweet->text.'<br>';
echo 'Created at - '.$tweet->created_at.'<br><br>';

}
}

?>
</body>
</html>


After that you just have to run the index file and see the results.