2009 Comments Off
Laboratorio: Twitter trends
Mi amigo Christian me ha comentado que la entrada anterior sobre Twitter sería más interesante si mostrara los datos sobre un término.
Pues dicho y hecho, tan sólo se necesitan dos scripts, uno para recuperar los datos y otro para mostrarlos. El primero habrá que ponerlo en el cron para que recupere los datos cada cierto tiempo (en mi ejemplo busco “google” cada 2 minutos).
<? php
function insertar($consulta, $ult) {
global $db;
$data = json_decode(file_get_contents('http://search.twitter.com/search?q='.urlencode($consulta).'&refresh=true&since_id='.$ult));
$n = isset($data->total) && $ult != $data->max_id? $data->total:0;
$db->queryExec('INSERT INTO estadisticas (fecha, n) values ('.time().', '.$n.')');
if (!$ult) $db->queryExec("INSERT INTO opciones (clave, valor) values ('ultimo', ".$data->max_id.")");
else $db->queryExec("UPDATE opciones SET valor = ".$data->max_id." where clave='ultimo' ");
}
$consulta = $_GET['q'];
// Limpio para poder usarlo en el nombre para la BD
$_consulta = preg_replace('/[^A-Z0-9]/i', '_', $consulta);
if ($db = new SQLiteDatabase($_consulta.'.db')) {
$q = @$db->query("SELECT valor FROM opciones Where clave='ultimo'");
if (!$q) {
$db->queryExec('CREATE TABLE estadisticas (fecha real, n real, PRIMARY KEY (fecha));');
$db->queryExec('CREATE TABLE opciones (clave text, valor text, PRIMARY KEY (clave));');
$q = $db->query("SELECT valor FROM opciones Where clave='ultimo'");
}
$r = $q->fetchAll(SQLITE_ASSOC);
$ult = 0;
if (!empty($r)) $ult = $r[0]['valor'];
insertar($consulta, $ult);
}
?>
Y el script que dibuja la gráfica es:
<? php
$desde = strtotime($_GET['desde']);
$hasta = strtotime($_GET['hasta']);
$consulta = $_GET['q'];
// Limpio para poder usarlo en el nombre para la BD
$_consulta = preg_replace('/[^A-Z0-9]/i', '_', $consulta);
if ($db = new SQLiteDatabase($_consulta.'.db')) {
$q = $db->query("SELECT fecha, n FROM estadisticas Where fecha>".$desde." and fecha<".$hasta);
$r = $q->fetchAll(SQLITE_ASSOC);
foreach($r as $item) {
$x[] = $item['n'];
$l[] = $item['fecha'];
}
}
header('Location: http://chart.apis.google.com/chart?chtt=Line+Chart&chts=000000,12&chs=1000x600&chf=bg,s,ffffff|c,s,ffffff&chxt=x,y&chxl=0:|'.implode('|', $l).'|1:|'.implode('|', $x).'&cht=lc&chd=t:75.00,16.66,0.00,8.33,100.00&chdl=Label+1&chco=0000ff&chls=1,1,0');
Actualización: Google Charts no deja meter muchos valores por lo que la gráfica de arriba sólo saca las 20 últimas actualizaciones