Twitter-LogoTwitter telah menjadi media social network yang sangat populer dan efektif yang sudah hampir menyamai popularitas facebook. Twitter menyediakan API (Application Programming Interface) yang sangat baik, sehingga memudahkan setiap orang untuk mengambil data dari twitter. Pengumpulan data dari twitter dapat digunakan untuk berbagai kebutuhan seperti : mengetahui popularitas kandidat pilkada atau pemilu, mendapat informasi mengenai popularitas suatu produk atau untuk yang sederhana dapat digunakan untuk melihat semua mention, retwit atas suatu account twitter tertentu.

Tulisan ini akan mengupas cara untuk membuat aplikasi sederhana mengenai proses penarikan data dari twitter menggunakan PHP dan API twitter.

Berikut adalah contoh hasil yang akan kita dapatkan :

  1. Setting untuk menuliskan account twitter yang akan ditarik datanya
    twitter1
  2. Mengisikan account twitter, contoh : jokowi
    twitter2
  3. Mengkonfirmasi untuk menarik dan menyimpan data
    twitter5
  4. Tampilan hasil tarikan data dari twitter untuk keywork : jokowi
    twitter4

Berikut adalah source code terkaitnya  :

Buatkan file config.php untuk koneksi database sebagai berikut :

<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'twitlist');
?>

Untuk itu, buatkan juga database twitlist yang terdiri dari 2 tabel, dengan script berikut

CREATE TABLE IF NOT EXISTS `param` (
 `urut` int(11) NOT NULL AUTO_INCREMENT,
 `paramid` varchar(20) NOT NULL,
 `paramvalue` varchar(50) NOT NULL,
 `userid` int(11) NOT NULL,
 PRIMARY KEY (`urut`)
) ;

CREATE TABLE IF NOT EXISTS `twitlog` (
 `urut` int(11) NOT NULL AUTO_INCREMENT,
 `twit` varchar(200) NOT NULL,
 `author` varchar(100) NOT NULL,
 `twitdate` datetime NOT NULL,
 `accounttwitter` varchar(50) NOT NULL,
 PRIMARY KEY (`urut`)
)  ;

Buat file kosong dan save sebagai inc_open_db, kemudian isikan script berikut :

<?
 $con = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
 if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db(DB_DATABASE, $con);
?>

Create file menu.php berikut :


<a href="settingtwitteraccount.php">Setting Account Twitter</a> | <a href="tarik_data_twitter.php" onclick="return confirm('Data sebelumnya akan dihapus?')">Import Twitter</a>

Untuk keperluan tampilan, berikut adalah file css yang dibutuhkan (loginmodule.css) :

body {
 font: 11px/1.4em Verdana, Arial, Helvetica, sans-serif;
}
h1 {
 color: #99CC00;
 margin: 0px 0px 5px;
 padding: 0px 0px 3px;
 font: bold 18px Verdana, Arial, Helvetica, sans-serif;
 border-bottom: 1px dashed #E6E8ED;
}
h2 {
 color: #99CC00;
 margin: 15px 0px 5px;
 padding: 0px 0px 3px;
 font: bold 14px Verdana, Arial, Helvetica, sans-serif;
 border-bottom: 1px dashed #E6E8ED;
}
a {
 color: #2D3954;
 font-size: 11px;
}
a:hover {
 color: #99CC00;
}

table {
 font: 11px/24px Verdana, Arial, Helvetica, sans-serif;
 border-collapse: collapse;
 width: 320px;
 }

th {
 padding: 0 0.5em;
 text-align: left;
 }

tr.yellow td {
 border-top: 1px solid #FB7A31;
 border-bottom: 1px solid #FB7A31;
 background: #FFC;
 }

td {
 border-bottom: 1px solid #CCC;
 padding: 0 0.5em;
 }

td:first-child {
 width: 190px;
 }

td+td {
 border-left: 1px solid #CCC;
 text-align: left;
 }

File berikut adalah untuk setting kata kunci apa yang akan di cari dari database twitter : settingtwitteraccount.php


<?php
 require_once('config.php');

?>
<html>
<head>
<title>Scoring</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Setting Account Twitter</h1>
<?php include("menu.php"); ?>

 <form action=settingtwitteraccount_result.php method=post>
 <input type=text name=accounttwitter value='' >
 <input type=submit value="Proses">
 </form>

<?

 include("inc_open_db.php");

$sql = "select * from param where userid=" . $_SESSION['SESS_MEMBER_ID'] . " and paramid='accounttwitter'";
 $result = mysql_query($sql,$con);

while ($row = mysql_fetch_array($result))
 {
 echo "account twitter yang di-score : " . $row['paramvalue'];
 }
 mysql_close($con);

?>

</body>
</html>

File settingtwitteraccount_result.php berikut adalah hasil dari proses pemilihan kata kunci dari proses sebelumnya di atas :

<?php
 //require_once('auth.php');
 require_once('config.php');

include("inc_open_db.php");

$sql = "select * from param where paramid='accounttwitter'";
 $result = mysql_query($sql,$con);
 $numrows = mysql_num_rows($result);
 if ($numrows>0)
 {
 $sql = "update param set paramvalue='" . $_POST['accounttwitter'] . "' where paramid='accounttwitter'";
 $result = mysql_query($sql,$con);
 }
 else
 {
 $sql = "insert into param (paramid,paramvalue) values ('accounttwitter','" . $_POST['accounttwitter'] . "')";
 $result = mysql_query($sql,$con);
 }
 header("Location: settingtwitteraccount.php");

?>

Dan file tarik_data_twitter.php berikut adalah file yang paling penting, yaitu yang berisikan mengenai proses penarikan data dari twitter sesuai dengan kata kunci yang telah diset sebelumnya :


<?
 require_once('config.php');
?>

<h1>Import Data Twitter</h1>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
<?php include("menu.php"); ?>
<?

include("inc_open_db.php");

 $sql = "select * from param where paramid='accounttwitter'";
 $result = mysql_query($sql,$con);

while ($row = mysql_fetch_array($result))
 {
 $q=$row['paramvalue'];
 }

$NUMITEMS = 100;
 $BLOGURL = "http://search.twitter.com/search.rss?q=" . urlencode($q) . "&rpp=$NUMITEMS";
 $TIMEFORMAT = "j F Y, g:ia";
 $CACHEFILE = "/tmp/" . md5($BLOGURL);
 $CACHETIME = 0.5; # hours

# Original PHP code by Chirp Internet: www.chirp.com.au
 # Please acknowledge use of this code by including this header.

function expandLinks(&$input)
 {
 # links matching the following regular expressions will be checked for redirects and expanded
 $domains = array(
 '[a-z0-9]{2,3}\.[a-z]{2}', '[a-z]{3,4}(url|ly)\.com'
 );
 if(preg_match_all("@http://((" . implode("|", $domains) . ")/[-a-z0-9]+)@i", $input, $matches)) {
 $matches = array_unique($matches[1]);
 foreach($matches as $shorturl) {
 $command = "curl --head " . escapeshellarg($shorturl) . " | awk '($1 ~ /^Location/){print $2}'";
 if($expandedurl = exec($command)) {
 $input = str_replace("http://$shorturl", htmlspecialchars($expandedurl), $input);
 }
 }
 }
 }

function updateFeed()
 {
 global $BLOGURL, $CACHEFILE;

ini_set('user_agent', "TheArtOfWeb (http://{$_SERVER['HTTP_HOST']})");
 if($feed_contents = file_get_contents($BLOGURL)) {
 # expand shortened urls
 expandLinks($feed_contents);

# write feed contents to cache file
 $fp = fopen($CACHEFILE, 'w');
 fwrite($fp, $feed_contents);
 fclose($fp);
 }
 }

echo "<p>Read the latest tweets mentioning <b>$q</b> as of ";
 if(file_exists($CACHEFILE)) {
 echo date('g:ia', filemtime($CACHEFILE)) . ' local time';
 } else {
 echo 'right now';
 }
 echo ":</p>\n\n";

# download the feed iff cached version is missing
 if(!file_exists($CACHEFILE)) updateFeed();

include "class.myrssparser.php";
 $rss_parser = new myRSSParser($CACHEFILE);

# read feed data from cache file
 $feeddata = $rss_parser->getRawOutput();
 extract($feeddata['RSS']['CHANNEL'][0], EXTR_PREFIX_ALL, 'rss');

# display feed items
 if($rss_ITEM) {
 echo "<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\">\n";
 foreach($rss_ITEM as $itemdata) {
 preg_match("/^(.*)@twitter\.com \((.*)\)$/", $itemdata['AUTHOR'], $regs);
 list($foo, $author, $name) = $regs;
 echo "<tr>\n";
 echo "<td><a title=\"$name\" href=\"http://twitter.com/$author\" target=\"_blank\"><img src=\"{$itemdata['GOOGLE:IMAGE_LINK']}\" width=\"48\" height=\"48\" border=\"0\" alt=\"$author\"></a></td>\n";
 echo "<td><p style=\"width: 600px; overflow: auto;\"><a href=\"http://twitter.com/$author\" target=\"_blank\">$author</a>: ";
 echo str_replace('<a ', '<a rel="nofollow" target="_blank" ', stripslashes($itemdata['DESCRIPTION']));
 echo "<br>\n";
 echo "<small><a style=\"text-decoration: none; color: inherit;\" href=\"{$itemdata['GUID']}\" target=\"_blank\">";
 echo date($TIMEFORMAT, strtotime($itemdata['PUBDATE']));
 echo "</a></small>";
 echo "</p></td>\n";
 echo "</tr>\n";
 $strsql="INSERT INTO twitlog (author,twit,twitdate,accounttwitter) VALUES ('". $itemdata['AUTHOR'] ."','" . $itemdata['DESCRIPTION'] . "','". date("Y-m-d H:i:s", strtotime($itemdata['PUBDATE'])) ."',0,'" . $q ."')";
 mysql_query($strsql);
 }
 echo "</table>\n\n";

}

# download the feed iff cached version is too old
 if((time() - filemtime($CACHEFILE)) > 3600 * $CACHETIME) {
 flush();
 updateFeed();
 }
 mysql_close($con);
?>

Untuk file class.myrssparser.php, silakan download disini