Posted by alct on Wed 18th Nov 19:15
download | new post | report as spam

  1. <?php
  2.  
  3. /*
  4. * A simple PHP get-latest-tweet script
  5. * Author : Andrew 'Akhilleus' Loconte
  6. * http://andreloconte.com
  7. * http://twitter.com/alct
  8. */
  9.  
  10. function latestTweet() {
  11.         $dir      = 'tw_cache/';
  12.         $fileName = 'latest.php';
  13.         $latest   = $dir . $fileName;
  14.  
  15.         $update     = @filemtime($latest);
  16.         $udpateFreq = $update + 600; // 10 minutes
  17.        
  18.         $user = 'USERNAME'; // username
  19.         $password = 'PASSWORD'; // password
  20.        
  21.         $ch = curl_init('https://twitter.com/statuses/user_timeline.xml');
  22.         curl_setopt($ch, CURLOPT_HEADER, 1);
  23.         curl_setopt($ch,CURLOPT_TIMEOUT, 30);
  24.         curl_setopt($ch,CURLOPT_USERPWD,$user . ':' . $password);
  25.         curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  26.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  27.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  28.        
  29.         if ((!file_exists($latest)) && ((curl_exec($ch)) === FALSE))
  30.         {
  31.                 return 'Houston, we\'ve got a problem.';
  32.         }
  33.         elseif (((file_exists($latest)) && (time() < $udpateFreq))
  34.         || ((curl_exec($ch)) === FALSE))
  35.         {
  36.                 $fileContent = fopen($latest, 'r');
  37.                 $latestTweet = fgets($fileContent);
  38.                 fclose($fileContent);
  39.        
  40.                 return htmlspecialchars($latestTweet);
  41.         }
  42.         else {
  43.                 $result = curl_exec($ch);
  44.                 $data   = strstr($result, '<?');
  45.  
  46.                 $xml = new SimpleXMLElement($data);
  47.  
  48.                 $latestTweet = $xml->status[0]->text;
  49.  
  50.                 if (!is_dir($dir)) { mkdir($dir, 0705); }
  51.  
  52.                 $fileContent = fopen($latest, 'w+');
  53.                 fputs($fileContent, $latestTweet);
  54.                 fclose($fileContent);
  55.  
  56.                 return htmlspecialchars($latestTweet);
  57.         }
  58. }
  59.  
  60. echo latestTweet();
  61.  
  62. ?>

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily
.
Syntax highlighting:

To highlight particular lines, prefix each line with @@
   Remember me