Creating a Lifestream With Gnip and PHP
As development on my cms has progressed, I have come to realize that I am not a prolific writer. However, I do love playing with new web services and technologies, so I have decided to push Nisaba towards a lifestream format. This will allow me to have fresh content on my site by interacting with online services I already use.
One of the hurdles in implementing a lifestream is scheduling the import of external data, such as flickr images, tweets, plurks, delicious bookmarks, etc. I did consider setting up a PHP script in a crontab, but this solution is less than desirable. Not all hosts give users their own crontab, plus manual configuration of cron isn’t exactly fun or easy.
Enter Gnip. Instead of continuously polling for feed updates, Gnip provides “push” updates to the data consumer. This allows for near real-time updates, a standardized update notification, and decreased server and network load. Gnip does have an API that allows for data producer registration and activity retrieval, but we’ll still need some code to handle the pushed activity streams. The following 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 postedif (!$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();
}
?>