Created
May 24, 2011 19:14
-
-
Save gknapp/989435 to your computer and use it in GitHub Desktop.
Backup your tweets with PHP
This file contains 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
<?php | |
/** | |
* Not my most graceful code, in fact this doesn't represent | |
* my coding style at all really but it serves a purpose and | |
* enabled me to backup 62 pages of tweets (1,223). | |
* | |
* Don't forget to change the username before you back up my | |
* feed by mistake :) | |
*/ | |
$username = 'g4egk'; | |
$page = 1; | |
$slurp = true; | |
$tweets = array(); | |
echo "Downloading page "; | |
while ($slurp) { | |
$fp = fopen( | |
sprintf('http://twitter.com/statuses/user_timeline/%s.xml?page=%s', $username, $page), | |
'rb' | |
); | |
$buffer = ''; | |
echo " ."; | |
if (!$fp || !is_resource($fp)) { | |
echo " read failed." . PHP_EOL; | |
break; | |
} | |
while (!feof($fp)) { | |
$buffer .= stream_get_contents($fp); | |
} | |
fclose($fp); | |
echo "."; | |
$xml = new SimpleXMLElement($buffer); | |
if (count($xml->status) < 1) | |
break; | |
foreach ($xml->status as $tweet) { | |
$tweets[] = array( | |
'time' => $tweet->created_at, | |
'tweet' => $tweet->text, | |
'tweet_id' => $tweet->id, | |
'reply_to' => $tweet->in_reply_to_status_id | |
); | |
} | |
echo ". " . $page; | |
$page++; | |
sleep(2); | |
} | |
echo " complete." . PHP_EOL; | |
$doc = new DOMDocument; | |
$doc->formatOutput = true; | |
$channel = $doc->createElement("channel"); | |
foreach ($tweets as $tweet) { | |
$link = $doc->createElement("link"); | |
$link->appendChild($doc->createTextNode($tweet['tweet_id'])); | |
$title = $doc->createElement("title"); | |
$title->appendChild($doc->createTextNode($tweet['tweet'])); | |
$desc = $doc->createElement("description"); | |
$desc->appendChild($doc->createTextNode($tweet['tweet'])); | |
$reply = $doc->createElement("reply_to"); | |
$reply->appendChild($doc->createTextNode($tweet['reply_to'])); | |
$time = strtotime($tweet['time']); | |
$pubDate = $doc->createElement("pubDate"); | |
$pubDate->appendChild( | |
$doc->createTextNode(date('r', $time)) | |
); | |
$item = $doc->createElement("item"); | |
$item->appendChild($title); | |
$item->appendChild($desc); | |
$item->appendChild($pubDate); | |
$item->appendChild($link); | |
$item->appendChild($reply); | |
$channel->appendChild($item); | |
} | |
$rss = $doc->createElement("rss"); | |
$rss->appendChild($channel); | |
$doc->appendChild($rss); | |
file_put_contents($username . '-feed.rss', $doc->saveXML()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment