1 <?php defined('SYSPATH') OR die('No direct access allowed.');
5 * $Id: feed.php 4152 2009-04-03 23:26:23Z ixmatus $
9 * @copyright (c) 2007-2008 Kohana Team
10 * @license http://kohanaphp.com/license.html
15 * Parses a remote feed into an array.
17 * @param string remote feed URL
18 * @param integer item limit to fetch
21 public static function parse($feed, $limit = 0)
23 // Check if SimpleXML is installed
24 if( ! function_exists('simplexml_load_file'))
25 throw new Kohana_User_Exception('Feed Error', 'SimpleXML must be installed!');
27 // Make limit an integer
28 $limit = (int) $limit;
30 // Disable error reporting while opening the feed
31 $ER = error_reporting(0);
33 // Allow loading by filename or raw XML string
34 $load = (is_file($feed) OR valid::url($feed)) ? 'simplexml_load_file' : 'simplexml_load_string';
37 $feed = $load($feed, 'SimpleXMLElement', LIBXML_NOCDATA);
39 // Restore error reporting
42 // Feed could not be loaded
46 // Detect the feed type. RSS 1.0/2.0 and Atom 1.0 are supported.
47 $feed = isset($feed->channel) ? $feed->xpath('//item') : $feed->entry;
52 foreach ($feed as $item)
54 if ($limit > 0 AND $i++ === $limit)
57 $items[] = (array) $item;
64 * Creates a feed from the given parameters.
66 * @param array feed information
67 * @param array items to add to the feed
68 * @param string define which format to use
69 * @param string define which encoding to use
72 public static function create($info, $items, $format = 'rss2', $encoding = 'UTF-8')
74 $info += array('title' => 'Generated Feed', 'link' => '', 'generator' => 'KohanaPHP');
76 $feed = '<?xml version="1.0" encoding="'.$encoding.'"?><rss version="2.0"><channel></channel></rss>';
77 $feed = simplexml_load_string($feed);
79 foreach ($info as $name => $value)
81 if (($name === 'pubDate' OR $name === 'lastBuildDate') AND (is_int($value) OR ctype_digit($value)))
83 // Convert timestamps to RFC 822 formatted dates
84 $value = date(DATE_RFC822, $value);
86 elseif (($name === 'link' OR $name === 'docs') AND strpos($value, '://') === FALSE)
88 // Convert URIs to URLs
89 $value = url::site($value, 'http');
92 // Add the info to the channel
93 $feed->channel->addChild($name, $value);
96 foreach ($items as $item)
98 // Add the item to the channel
99 $row = $feed->channel->addChild('item');
101 foreach ($item as $name => $value)
103 if ($name === 'pubDate' AND (is_int($value) OR ctype_digit($value)))
105 // Convert timestamps to RFC 822 formatted dates
106 $value = date(DATE_RFC822, $value);
108 elseif (($name === 'link' OR $name === 'guid') AND strpos($value, '://') === FALSE)
110 // Convert URIs to URLs
111 $value = url::site($value, 'http');
114 // Add the info to the row
115 $row->addChild($name, $value);
119 return $feed->asXML();