Created
May 24, 2012 21:22
-
-
Save swvitaliy/2784307 to your computer and use it in GitHub Desktop.
rss generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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