Creating a Lifestream With Gnip and PHP

tags: , , ,

As devel­op­ment on my cms has pro­gressed, I have come to real­ize that I am not a pro­lific writer. How­ever, I do love play­ing with new web ser­vices and tech­nolo­gies, so I have decided to push Nis­aba towards a lifestream for­mat. This will allow me to have fresh con­tent on my site by inter­act­ing with online ser­vices I already use.

One of the hur­dles in imple­ment­ing a lifestream is sched­ul­ing the import of exter­nal data, such as flickr images, tweets, plurks, deli­cious book­marks, etc. I did con­sider set­ting up a PHP script in a crontab, but this solu­tion is less than desir­able. Not all hosts give users their own crontab, plus man­ual con­fig­u­ra­tion of cron isn’t exactly fun or easy.

Enter Gnip. Instead of con­tin­u­ously polling for feed updates, Gnip pro­vides “push” updates to the data con­sumer. This allows for near real-​time updates, a stan­dard­ized update noti­fi­ca­tion, and decreased server and net­work load. Gnip does have an API that allows for data pro­ducer reg­is­tra­tion and activ­ity retrieval, but we’ll still need some code to han­dle the pushed activ­ity streams. The fol­low­ing should get you started.

<?php

// Database connection information
$host = 'localhost';
$user = 'gnip';
$pass = 'gnip';
$db = 'gnip';
$table = 'activity';

// Read raw post data
$input = fopen('php://input','rb');
$xml = stream_get_contents($input);
fclose($input);

// Parse the posted XML activity feed & exit if no info was posted
if (!$activities = simplexml_load_string($xml)) {
    exit();
}

try {

    // Create database connection
    $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);

    // Prepare the insert statement
    $insert = $pdo->prepare('INSERT INTO ' . $table
        . ' (time, uid, type, guid, publisher_name) '
        . ' VALUES '
        . '( :time, :uid, :type, :guid, :publisher_name )'
    );

    // Insert the activities into the database
    foreach ($activities as $activity) {
        
        $insert->bindValue(':time', $activity['at']);
        $insert->bindValue(':uid', $activity['uid']);
        $insert->bindValue(':type', $activity['type']);
        $insert->bindValue(':guid', $activity['guid']);
        $insert->bindValue(':publisher_name', $activity['publisher.name']);
            
        $insert->execute();
            
    }
    
} catch (PDOException $e) {

    // You'll probably want to log this message instead of echoing it
    echo $e->getMessage();

}

?>
view raw gistfile1.php This Gist brought to you by GitHub.

Feedback