diff --git a/lib/Creator/JSONCreator.php b/lib/Creator/JSONCreator.php new file mode 100644 index 0000000..161d3b4 --- /dev/null +++ b/lib/Creator/JSONCreator.php @@ -0,0 +1,66 @@ + + */ +class JSONCreator extends FeedCreator +{ + /** @inheritdoc */ + public function createFeed() + { + $data = array(); + + $data['version'] = 'https://jsonfeed.org/version/1.1'; + $data['title'] = (string)$this->title; + $data['home_page_url'] = (string)$this->link; + $data['feed_url'] = (string)$this->syndicationURL; + $data['description'] = (string)$this->description; + $data['user_comment'] = 'Created by ' . FEEDCREATOR_VERSION; + if ($this->image != null) { + $data['icon'] = $this->image->url; + } + if ($this->language != '') { + $data['language'] = $this->language; + } + + $data['items'] = array(); + foreach ($this->items as $item) { + $entry = array(); + $entry['id'] = $item->guid ? (string)$item->guid : (string)$item->link; + $entry['url'] = (string)$item->link; + if ($item->source) { + $entry['external_url'] = (string)$item->source; + } + $entry['title'] = strip_tags((string)$item->title); + $entry['content_text'] = strip_tags((string)$item->description); + $entry['content_html'] = (string)$item->description; + $entry['date_published'] = (new FeedDate($item->date))->iso8601(); + if ($item->author) { + // We only support one author, JSONFeed 1.1 accepts multiple + $entry['authors'] = array(array('name' => (string)$item->author)); + // 1.0 only supported one, for compatibility we set it as well + $entry['author'] = array('name' => (string)$item->author); + } + if ($item->category) { + $entry['tags'] = (array)$item->category; + } + if ($item->enclosure) { + // We only support one enclosure, JSONFeed 1.1 accepts multiple + $entry['attachments'] = array( + array( + 'url' => $item->enclosure['url'], + 'mime_type' => $item->enclosure['type'], + 'size_in_bytes' => $item->enclosure['length'] + ) + ); + } + + $data['items'][] = $entry; + } + + return json_encode($data); + } +} diff --git a/lib/UniversalFeedCreator.php b/lib/UniversalFeedCreator.php index 297d382..53a8885 100644 --- a/lib/UniversalFeedCreator.php +++ b/lib/UniversalFeedCreator.php @@ -88,6 +88,10 @@ protected function _setFormat($format) $this->_feed = new JSCreator(); break; + case "JSON": + $this->_feed = new JSONCreator(); + break; + default: $this->_feed = new RSSCreator091(); break; diff --git a/test/Creator/JSONCreatorTest.php b/test/Creator/JSONCreatorTest.php new file mode 100644 index 0000000..e707a0a --- /dev/null +++ b/test/Creator/JSONCreatorTest.php @@ -0,0 +1,24 @@ +description = 'Feed Description'; + $item = new FeedItem(); + $item->date = time(); + $item->category = array('1', '2'); + $creator->addItem($item); + + $feed = $creator->createFeed('JSON'); + + $parsed = json_decode($feed, true); + $this->assertEquals('Feed Description', $parsed['description']); + } +}