Want more features on Pastebin? Sign Up, it's FREE!
Guest

My PHP Script

By: a guest on Mar 2nd, 2014  |  syntax: PHP  |  size: 1.04 KB  |  views: 100  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2. header('Content-type: text/xml');
  3. $threshold = 600; // 10 minutes in seconds
  4. $myApiUrl = 'http://myapisite.com/rss'; //rss feed
  5.  
  6. $file = 'filename.txt';
  7. $fmtime = filemtime($file);
  8. $timeDiff = time() - $fmtime;
  9.  
  10. /* gets the rss data from my api */
  11. function get_data_from_api($url) {
  12.         $ch = curl_init();
  13.         $timeout = 20;
  14.         curl_setopt($ch, CURLOPT_URL, $url);
  15.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  16.         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  17.         $data = curl_exec($ch);
  18.         curl_close($ch);
  19.         return $data;
  20. }
  21.  
  22. // If file exists (fmtime is true) and timediff is lower or equal to threshold, send file.
  23. if ($fmtime && $timeDiff <= $threshold) {
  24.         $apiData = file_get_contents($file);
  25.         echo $apiData;
  26. // else if file doesn't exist or timediff is over threshold, fetch api and save to file.
  27. } elseif (!$fmtime || $timeDiff > $threshold) {
  28.         $apiData = get_data_from_api($myApiUrl);
  29.         if($apiData !== false){
  30.                 file_put_contents($file, $apiData);
  31.                 echo $apiData;
  32.         }
  33. } else {
  34.         // Do whaetever if nothing else happens
  35. }
  36.  
  37. ?>
clone this paste RAW Paste Data