Skip to content

Instantly share code, notes, and snippets.

@cowlby
Created April 19, 2011 00:29
Show Gist options
  • Save cowlby/926584 to your computer and use it in GitHub Desktop.
Save cowlby/926584 to your computer and use it in GitHub Desktop.
Scrapes the Potato Counter off the Aperture Science website using Zend_Http_Client as the client, DOMDocument as the DOM browser, and Zend_Db as the interface to a simple database.
CREATE TABLE `potatoes` (
`id` smallint(11) NOT NULL AUTO_INCREMENT,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`count` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=64 DEFAULT CHARSET=latin1;
<?php
// Add Zend Framework to the include path. I have it in ./lib/vendor/Zend
$libDir = realpath(__DIR__.'/lib');
set_include_path($libDir.'/vendor/'.PATH_SEPARATOR.get_include_path());
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
// Zend_Db makes inserts a piece of cake. /tmp/mysql.sock is the mysql.sock location in OS X.
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => 'localhost',
'username' => 'glados',
'password' => '',
'unix_socket' => '/tmp/mysql.sock',
'dbname' => 'aperture_science'
));
// GET the counter page.
$url = 'http://www.aperturescience.com/glados@home/';
$client = new Zend_Http_Client($url);
$client->setMethod(Zend_Http_Client::GET);
$response = $client->request();
if (!$response->isSuccessful()) {
die('Could not get the potato count.');
}
// Load the HTML into the DOM parser.
$doc = new DOMDocument();
$doc->loadHTML($response->getBody());
$potatoesEl = $doc->getElementById('potatoes');
// Insert the count into the database. No "id" (AUTO_INCREMENT) or "created_at" (CURRENT_TIMESTAMP) needed.
$db->insert('potatoes', $array(
'count' => str_replace(',', '', $potatoesEl->nodeValue)
));
echo $db->lastInsertId() . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment