Skip to content

Instantly share code, notes, and snippets.

@mylk
Created October 16, 2016 15:28
Show Gist options
  • Save mylk/dc7c64aefe19ac47651dd35e2b2a4895 to your computer and use it in GitHub Desktop.
Save mylk/dc7c64aefe19ac47651dd35e2b2a4895 to your computer and use it in GitHub Desktop.
A class that generates an RSS feed from an array of entities
<?php
/*
* Installation (Symfony):
* =======================
* # services.yml
* services:
* # ...
* acme.rss_feed_generator:
* class: Acme\AcmeBundle\Service\RssFeedGeneratorService
* calls: [ [setupDependencies, [%rss_feed_title%, %rss_feed_url_homepage%, %rss_feed_url_feed%, %rss_feed_description%]] ]
*
* Usage (Symfony):
* ================
* $rssFeedGenerator = $this->get("acme.rss_feed_generator");
* $rssFeed = $rssFeedGenerator->generate($posts);
* $response = new Response($rssFeed);
* $response->headers->set("Content-Type", "text/xml; charset=UTF-8");
* return $response
*/
namespace Acme\AcmeBundle\Service;
class RssFeedGeneratorService
{
private $title;
private $urlHomepage;
private $urlFeed;
private $description;
public function setupDependencies($title, $urlHomepage, $urlFeed, $description)
{
$this->title = $title;
$this->urlHomepage = $urlHomepage;
$this->urlFeed = $urlFeed;
$this->description = $description;
}
public function generate($posts)
{
$feed = new \SimpleXMLElement("<rss xmlns:atom=\"http://www.w3.org/2005/Atom\" />");
$feed->addAttribute("version", "2.0");
$channel = $feed->addChild("channel");
$atomLink = $channel->addChild("link", "", "http://www.w3.org/2005/Atom");
$atomLink->addAttribute("href", $this->urlFeed);
$atomLink->addAttribute("rel", "self");
$atomLink->addAttribute("type", "application/rss+xml");
$channel->addChild("title", $this->title);
$channel->addChild("link", $this->urlHomepage);
$channel->addChild("description", $this->description);
foreach ($posts as $post) {
$item = $channel->addChild("item");
$item->addChild("title", $post->getTitle());
// set first 150 chars as the description
$item->addChild("description", \substr($post->getContent(), 0, 150));
$item->addChild("guid", \sprintf("http://example.com/post/%s", $post->getId()));
// convert date to the rss standard
$item->addChild("pubDate", $post->getCreatedAt()->format("r"));
}
return $feed->asXML();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment