Guest User

getFeed with sorting

a guest
Jul 8th, 2011
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.33 KB | None | 0 0
  1. <?php
  2. /**
  3.  * getFeed
  4.  *
  5.  * A simple snippet to retrieve an RSS feed and iterate the feed items using a Chunk.
  6.  *
  7.  * @author Jason Coward <[email protected]>
  8.  * @author Shaun McCormick <[email protected]>
  9.  *
  10.  * @version 1.0.0-beta
  11.  * @copyright Copyright 2010 by Jason Coward
  12.  * @license http://www.gnu.org/licenses/gpl.txt GPLv3
  13.  */
  14. if (!defined('MAGPIE_OUTPUT_ENCODING')) {
  15.     $outputEncoding = $modx->getOption('outputEncoding',$scriptProperties,'UTF-8');
  16.     define('MAGPIE_OUTPUT_ENCODING',$outputEncoding);
  17. }
  18. $limit = isset($limit) ? (integer) $limit : 0;
  19. $offset = isset($offset) ? (integer) $offset : 0;
  20. $totalVar = !empty($totalVar) ? $totalVar : 'total';
  21. $total = 0;
  22. $output = array();
  23. if (!empty($url) && $modx->getService('rss', 'xmlrss.modRSSParser')) {
  24.     $rss = $modx->rss->parse($url);
  25.     if (!empty($rss) && isset($rss->items)) {
  26.         if (!empty($sortby)) {
  27.             $sortby_array = array();
  28.             $path = explode(".", $sortby);
  29.             foreach ($rss->items as $item) {
  30.                 foreach($path as $node) $item = $item[$node];
  31.                 $sortby_array[] = $item;
  32.             }
  33.                   $sortdir = isset($sortdir) ? $sortdir : 'DESC';
  34.             if ($sortdir == 'ASC') {
  35.                 array_multisort($sortby_array, SORT_ASC, $rss->items);
  36.             } else {
  37.                 array_multisort($sortby_array, SORT_DESC, $rss->items);
  38.             }
  39.         }
  40.         $total = count($rss->items);
  41.         $modx->setPlaceholder($totalVar, $total);
  42.         $itemIdx = 0;
  43.         $idx = 0;
  44.         while (list($itemKey, $item) = each($rss->items)) {
  45.             if ($idx >= $offset) {
  46.                 if (!empty($tpl)) {
  47.                     $output[] = $modx->getChunk($tpl, $item);
  48.                 } else {
  49.                     $output[] = '<pre>'.$idx.': ' . print_r($item, true) . '</pre>';
  50.                 }
  51.                 $itemIdx++;
  52.                 if ($limit > 0 && $itemIdx+1 > $limit) break;
  53.             }
  54.             $idx++;
  55.         }
  56.     } else {
  57.         $modx->log(modX::LOG_LEVEL_ERROR, "Error parsing RSS feed at {$url}", '', 'getFeed', __FILE__, __LINE__);
  58.     }
  59. }
  60. $output = implode("\n", $output);
  61.  
  62. if (!empty($scriptProperties['toPlaceholder'])) {
  63.     $modx->setPlaceholder($scriptProperties['toPlaceholder'],$output);
  64.     return '';
  65. }
  66. return $output;
Advertisement
Add Comment
Please, Sign In to add comment