Interfaccia in PHP per Runkeeper e Sportstracklive | Flavio's blog


Interfaccia in PHP per Runkeeper e Sportstracklive

Qualche giorno fa ho finalmente rispolverato la bicicletta e, approfittando del bel tempo, ho voluto fare un lungo giro costeggiando il mare.

Visto che il contachilometri era scarico, ho cercato qualche App per Android che sfruttasse il GPS per registrare il percorso, la velocità, l’altitudine, e così via. Runkeeper è subito saltato all’occhio: grafica accattivante, possibilità di condivisione social, App gratuita (anche se migliorabile).
Simile a Runkeeper, anche Sportstracklive registra le vostre performance. Rispetto al primo, però, ha un sito meno accattivante, ed una App per Android di gran lunga migliore (anche se a pagamento).

Ho installato l’App, fatti i miei bei 35km, ed a casa ho caricato il mio percorso sul sito web di Runkeeper.
Tuttavia, nè Runkeeper nè Sportstracklive offrono alcuna possibilità per integrare le statistiche della propria corsa sul proprio sito web (mentre è possibile condividerla via Facebook o Twitter). Inoltre, non offrono alcuna API per interagire con i loro dati.

In pochi minuti liberi ho scritto una piccola applicazione in PHP, che permette di mostrare nella mia homepage le statistiche relative all’ULTIMA mia attività, corsa o bicicletta che sia.

E’sufficiente inserire il proprio username, impostare il tempo di validità della cache (per evitare di sovraccaricare il sito), e potrete visualizzare subito le vostre statistiche!

Un esempio, preso dalla mia homepage:

Interfaccia PHP per Runkeeper in funzione

Interfaccia PHP per Runkeeper in funzione

Andiamo a dare un veloce sguardo al codice:

<?
/* Sportstracklive.com data parser. It automatically shows data from the LAST activity for a given username. Set your username, cache file name, and expiration time of the cachefile.
(c) Flapane.com - Feb-2013*/

define('SPORTSTRACK_USER','type_your_username');        //Runkeeper Username
$expiretime=6;          // cache expire time in hours
$cachename="sportstracklive.cache"; //name of the cachefile

//create the cachefile if it doesn't exist
if (!file_exists($cachename)) {
     $create = fopen($cachename, 'w');
      chmod ("$cachename", 0644); //set chmod 644
     fclose($create);
}

// Is the file older than $expiretime, or the file is new/empty?
$FileAge = time() - filectime($cachename);    // Calculate file age in seconds
if ($FileAge > ($expiretime * 3600) || 0 == filesize($cachename))
{
    include_once('simple_html_dom.php');
    $opts = array(
  'http'=>array(
    'user_agent'=>'Mozilla/5.0 (Windows; U; Windows NT 5.1; en; rv:1.9.2.3) Gecko/20100401 MRA 5.6 (build 03278) Firefox/3.6.3 (.NET CLR 3.5.30729)',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
  )
);
    $context = stream_context_create($opts);    //create an useragent for simple_html_dom
    $html = file_get_html('http://www.sportstracklive.com/search?what=user%3A'.SPORTSTRACK_USER.'&search=Search', 0, $context);
    $link = $html->find('.likeh4 lightGrey.', 0)->find('a', 0)->href;    // Get the last activity link
    $link2 = file_get_html('http://www.sportstracklive.com'.$link, 0, $context);
    $activity_table = $html->find('td', 1);    // Get the activity table stats
    $activity_table2 = $link2->find('table', 7);    //get other stats
    $activity_table3 = $link2->find('table', 8);    //get other stats (calories)

    $activity_date = strip_tags($activity_table->find('.lightGrey', 1)); //last activity data
    $category= strip_tags($link2->find('.likeh2', 0)); //activty type
    $distance= strip_tags($activity_table->find('.likeh2', 6)); //total distance
    $moving_time= strip_tags($activity_table2->find('.likeh4', 2)); //total moving time
    $avg_speed= strip_tags($activity_table2->find('.likeh4', 3)); //average speed
    $avg_time_km= strip_tags($activity_table2->find('.likeh4', 4)); //average moving pace
    $calories= strip_tags($activity_table3->find('.likeh4', 0)); //calories

    // Now refresh the cachefile with newer content

    $stats = '<a href="http://www.sportstracklive.com'.$link.'" target="_blank">Ultima attivit&agrave;:<b> '.$activity_date.'</b></a><br />Tipo di attivit&agrave;:<b> '.$category.'</b><br />Distanza totale:<b> '.$distance.'</b><br />Durata:<b> '.$moving_time.'</b><br />Velocit&agrave; media:<b> '.$avg_speed.'</b><br />Tempo medio sul Km:<b> '.$avg_time_km.'</b><br />Calorie bruciate:<b> '.$calories.'</b><br />';

    $handle = fopen($cachename, 'wb');
    fwrite($handle, $stats);            
}

//cachefile is fresh enough... outputting data
$data=file_get_contents($cachename);
echo $data;
?>

Come detto sopra, basterà impostare il proprio username. Per comodità, ho deciso di aggiornare la cache ogni 12 ore (720 minuti), tempo più che sufficiente, visto che difficilmente vi allenerete due volte al giorno!

Potete scaricare il file zip con tutto il necessario per mostrare le vostre statistiche, a questi indirizzi:

Runkeeper PHP parser

Sportstracklive PHP parser

Feedback, commenti e giudizi, sono i benvenuti!



1 Commento »

Per piacere accetta i cookie di terze parti per poter commentare il post! Il pulsante CAMBIA LE SCELTE DEI COOKIE si trova nel footer del sito. / In order to comment this post, please accept the third party cookies! The button CAMBIA LE SCELTE DEI COOKIE is in the footer of the website.