0xDEADBEEF

RSS odkazy
««« »»»

RSS in PHP

26. 10. 2020 #RSS #PHP #kód #en

RSS isn't complicated and there's no real reason why it should be omitted from any website. Perhaps not many people will use it, but they will love you for it and what's more – the necessary effort to implement it is so miniscule, there's really no excuse.

Sadly, when you search for tutorials on how to do RSS in PHP, the results are rather archaic and not very good. Most likely XML is printed manually without any escaping which is not a good idea. Code like that can produce invalid XML and some readers refuse to parse it entirely and the end result is the same as if there was no RSS present at all.

This article is my effort to rectify this sorry state of affairs. What follows is a simple script to generate minimal but useful RSS feed. Take it, use it, copy it, change it, it's so trivial, I would be ashamed to claim licence any other that public domain.

class RSS {
  private $rss;

  function __construct(string $title, string $description = '', string $link = '') {
    $this->rss = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><rss version="2.0"/>');
    $this->rss->channel->title = $title;
    $this->rss->channel->description = $description;
    $this->rss->channel->link = $link;
  }

  function addItem(string $title, string $url, string $body, \DateTimeInterface $date): SimpleXMLElement {
    $item = $this->rss->channel->addChild('item');
    $item->title = $title;
    $item->guid = $url;
    $item->guid['isPermaLink'] = 'true';
    $item->description = $body;
    $item->pubDate = $date->format(DATE_RSS);
    return $item;
  }

  function toString(): string {
    return $this->rss->asXML();
  }
}
píše k47 (@kaja47, k47)