Created
May 10, 2011 00:41
-
-
Save funkatron/963729 to your computer and use it in GitHub Desktop.
a PHP script to capture twitter source data from the streaming API into MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/dh/cgi-system/php5.cgi -q | |
| <?php | |
| $TWITTER_USERNAME = 'foo'; | |
| $TWITTER_PASSWORD = 'bar'; | |
| $PDO_CONN_URL = 'mysql:host=hostname;dbname=db_name', 'username', 'password'; | |
| set_time_limit(0); | |
| function getLinkFromHref($str) { | |
| return htmlspecialchars(preg_replace('/(<a href=")([^"]+)"(.*)/i', '$2', $str), ENT_QUOTES, 'UTF-8'); | |
| } | |
| function make_source_doc($doc) { | |
| $newdoc->id = (int)$doc->id; | |
| $newdoc->unixtime = (int)strtotime($doc->created_at); | |
| $newdoc->source_link = getLinkFromHref($doc->source); | |
| $newdoc->source_name = strtolower(strip_tags($doc->source)); | |
| $doc = $newdoc; | |
| unset($newdoc); | |
| return $doc; | |
| } | |
| $url = 'http://'.$TWITTER_USERNAME.':'.$TWITTER_PASSWORD.'@stream.twitter.com/1/statuses/sample.json'; | |
| $pdo = new PDO($PDO_CONN_URL); | |
| $sth = $pdo->prepare('insert into twitter_sources values (?, ?, ?, ?)'); | |
| $fp = fopen($url, r); | |
| while (!feof($fp)) { | |
| $jsonitem = fgets($fp, 4096); | |
| //echo $jsonitem."\n"; | |
| $item = make_source_doc(json_decode($jsonitem)); | |
| $params = array($item->id, $item->unixtime, $item->source_link, $item->source_name); | |
| $rs = $sth->execute( $params ); | |
| if (!$rs) { | |
| echo "insert failed!\n"; | |
| print_r($sth->errorInfo()); | |
| print_r($params); | |
| $sth->debugDumpParams(); | |
| } | |
| } | |
| fclose($fp); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment