Skip to content

Instantly share code, notes, and snippets.

@swvitaliy
Created May 24, 2012 21:22
Show Gist options
  • Save swvitaliy/2784307 to your computer and use it in GitHub Desktop.
Save swvitaliy/2784307 to your computer and use it in GitHub Desktop.
rss generator
<?php
class RssGenerator {
public static $rssFields = array('title', 'link', 'description', 'language', 'pubDate',
'lastBuildDate', 'docs', 'generator', 'managingEditor', 'webMaster');
public static $feedFields = array ('title', 'link', 'description', 'pubDate');
private $options = array();
private $feeds = array();
protected function expect (array $array, $fields, $extends = false) {
$result = array();
foreach ($fields as $field) {
if (!array_key_exists($field, $array)) {
throw new Exception ("field \"{$field}\" unexpected");
}
$result [$field] = $array[$field];
}
if (!$extends && count($result)<count($array)) {
throw new Exception("unexpected rssFields");
}
return $result;
}
public function __construct(array $options = null) {
if (!is_null($options)) {
$this->setOptions($options);
}
}
public function setOption ($name, $value) {
$this->setOptions(array($name => $value));
}
public function setOptions (array $options) {
$this->options = array_merge($this->options,
$this->expect($options, self::$rssFields));
}
public function clearFeeds () {
$this->feeds = array();
}
public function getFeeds () {
return $this->feeds;
}
public function addFeeds (array $data) {
foreach ($data as $feed) {
$this->addFeed($feed);
}
}
public function addFeed (array $feed) {
$feed = $this->expect($feed, self::$feedFields, true);
$this->feeds [] = $feed;
}
public function makeXml() {
var_dump($this->options);
var_dump($this->feeds);
$xml = simplexml_load_string('<rss></rss>');
$xml->addAttribute('version', '2.0');
$chanel = $xml->addChild('chanel');
foreach ($this->options as $name=>$value) {
$chanel->addChild($name, $value);
}
foreach ($this->feeds as $feed) {
$xmlFeed = $chanel->addChild('item');
foreach ($feed as $name => $value) {
$xmlFeed->addChild($name, $value);
}
}
return $xml->asXML();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment