Skip to content

Commit

Permalink
added universal $feed->load() [Closes #9]
Browse files Browse the repository at this point in the history
RSS has items in $feed->items, Atom in $feed->entry
  • Loading branch information
dg committed Jul 2, 2015
1 parent 0e26bd3 commit c53896d
Showing 1 changed file with 41 additions and 14 deletions.
55 changes: 41 additions & 14 deletions src/Feed.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,25 @@ class Feed
protected $xml;


/**
* Loads RSS or Atom feed.
* @param string
* @param string
* @param string
* @return Feed
* @throws FeedException
*/
public static function load($url, $user = NULL, $pass = NULL)
{
$xml = self::loadXml($url, $user, $pass);
if ($xml->channel) {
return self::fromRss($xml);
} else {
return self::fromAtom($xml);
}
}


/**
* Loads RSS feed.
* @param string RSS feed URL
Expand All @@ -29,12 +48,31 @@ class Feed
*/
public static function loadRss($url, $user = NULL, $pass = NULL)
{
$xml = self::loadXml($url, $user, $pass);
return self::fromRss(self::loadXml($url, $user, $pass));
}


/**
* Loads Atom feed.
* @param string Atom feed URL
* @param string optional user name
* @param string optional password
* @return Feed
* @throws FeedException
*/
public static function loadAtom($url, $user = NULL, $pass = NULL)
{
return self::fromAtom(self::loadXml($url, $user, $pass));
}


private static function fromRss(SimpleXMLElement $xml)
{
if (!$xml->channel) {
throw new FeedException('Invalid feed.');
}

self::adjustNamespaces($xml->channel);
self::adjustNamespaces($xml);

foreach ($xml->channel->item as $item) {
// converts namespaces to dotted tags
Expand All @@ -47,24 +85,14 @@ public static function loadRss($url, $user = NULL, $pass = NULL)
$item->timestamp = strtotime($item->pubDate);
}
}

$feed = new self;
$feed->xml = $xml->channel;
return $feed;
}


/**
* Loads Atom feed.
* @param string Atom feed URL
* @param string optional user name
* @param string optional password
* @return Feed
* @throws FeedException
*/
public static function loadAtom($url, $user = NULL, $pass = NULL)
private static function fromAtom(SimpleXMLElement $xml)
{
$xml = self::loadXml($url, $user, $pass);
if (!in_array('http://www.w3.org/2005/Atom', $xml->getDocNamespaces(), TRUE)
&& !in_array('http://purl.org/atom/ns#', $xml->getDocNamespaces(), TRUE)
) {
Expand All @@ -75,7 +103,6 @@ public static function loadAtom($url, $user = NULL, $pass = NULL)
foreach ($xml->entry as $entry) {
$entry->timestamp = strtotime($entry->updated);
}

$feed = new self;
$feed->xml = $xml;
return $feed;
Expand Down

0 comments on commit c53896d

Please sign in to comment.