# PHP RSS documentation (v8.6.x)

> Canonical: https://pharaonic.dev/packages/php/rss/8.6.x  
> Version: v8.6.x (latest release 8.6.0, 2026-12-01)  
> Install: composer require pharaonic/php-rss  
> Requires: PHP 8.6  
> Repository: https://github.com/Pharaonic/php-rss  
> All versions: https://pharaonic.dev/packages/php/rss/8.6.x.md https://pharaonic.dev/packages/php/rss/8.5.x.md https://pharaonic.dev/packages/php/rss/8.4.x.md https://pharaonic.dev/packages/php/rss/8.3.x.md https://pharaonic.dev/packages/php/rss/8.2.x.md https://pharaonic.dev/packages/php/rss/8.1.x.md https://pharaonic.dev/packages/php/rss/8.0.x.md

:::badges
- PHP Package {color=blue}
- v8.6.0 {color=green}
- MIT License {color=purple}
:::

# PHP RSS

PHP RSS is a lightweight RSS 2.0 feed generator for PHP 8. You describe the channel and its items with a fluent `Feed` and `Item` API, and `toXml()` returns a well-formed, specification-ordered XML document. It has no Composer dependencies beyond `ext-xmlwriter`, validates everything before writing, and supports the Atom, Content, Dublin Core, and Media RSS namespaces out of the box.

:::features
### Fluent Feed Builder
Every RSS 2.0 channel and item element is one chained method on `Feed` or `Item`.

### Always Well-Formed
Invalid UTF-8, XML control characters, and `]]>` in CDATA are rejected or handled, never written as broken XML.

### Namespaced Extensions
Built-in `atom:link`, `content:encoded`, `dc:creator`, and Media RSS elements, with namespaces declared once on the root.

### Your Own Extensions
Implement one small `Extension` contract to add any XML namespace, such as iTunes or GeoRSS.

### Podcasts and Media
Enclosures, `media:content`, and thumbnails cover podcast and video feeds.

### Clear Exceptions
Every error extends `RssException` and tells you exactly which field is wrong.
:::

:::info Quick Tip
`toXml()` only returns a string. It never sends HTTP headers, so you stay in control of the `Content-Type` and caching headers your application sends.
:::

## Installation

Install the package with Composer. There is no configuration file to publish and nothing to register.

### Requirements

- PHP 8.6
- The `xmlwriter` extension (`ext-xmlwriter`), bundled with most PHP builds

You can check that the extension is enabled with:

```bash title="Terminal" no-line-numbers
php -m | grep -i xmlwriter
```

### Composer Installation

```bash title="Terminal" no-line-numbers
composer require pharaonic/php-rss
```

### Namespace

Every class lives under the `Pharaonic\RSS` namespace:

| Namespace | Contains |
| --- | --- |
| `Pharaonic\RSS` | `Feed`, `Item` |
| `Pharaonic\RSS\Elements` | `Category`, `Guid`, `Enclosure`, `Image`, `Source`, `Cloud`, `TextInput`, `Day`, `CloudProtocol` |
| `Pharaonic\RSS\Extensions\*` | Atom, Content, Dublin Core, and Media RSS elements |
| `Pharaonic\RSS\Contracts` | `Extension` |
| `Pharaonic\RSS\Exceptions` | `RssException` and its subclasses |
| `Pharaonic\RSS\Writer` | `RssWriter`, `Xml`, `NamespaceRegistry`, `DateFormatter` |

:::success Installation Complete
You're all set! Head to [Basic Usage](#basic-usage) to build your first feed.
:::

## Basic Usage

A feed is a `Feed` (the RSS `<channel>`) holding any number of `Item` objects. Both are created with `make()` and configured with chained setters.

### Your First Feed

A channel needs a title, a link, and a description. Each item needs at least a title or a description.

```php title="public/rss.php"
use Pharaonic\RSS\Feed;
use Pharaonic\RSS\Item;

$cairo = new DateTimeZone('Africa/Cairo');

$feed = Feed::make()
    ->title('Pharaonic Blog')
    ->link('https://pharaonic.dev/blog')
    ->description('News & releases from the Pharaonic team.')
    ->language('en-US')
    ->lastBuildAt(new DateTimeImmutable('2026-10-06 12:00:00', $cairo));

$feed->addItem(
    Item::make()
        ->title('PHP RSS rebuilt')
        ->link('https://pharaonic.dev/blog/php-rss-rebuilt')
        ->description('<p>A modern <strong>RSS 2.0</strong> generator for PHP.</p>')
        ->category('PHP')
        ->guid('https://pharaonic.dev/blog/php-rss-rebuilt')
        ->publishedAt(new DateTimeImmutable('2026-10-06 10:00:00', $cairo))
);

header('Content-Type: application/rss+xml; charset=UTF-8');
echo $feed->toXml();
```

The output looks like this:

```xml title="Output" no-copy
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>Pharaonic Blog</title>
    <link>https://pharaonic.dev/blog</link>
    <description>News &amp; releases from the Pharaonic team.</description>
    <language>en-US</language>
    <lastBuildDate>Tue, 06 Oct 2026 12:00:00 +0300</lastBuildDate>
    <item>
      <title>PHP RSS rebuilt</title>
      <link>https://pharaonic.dev/blog/php-rss-rebuilt</link>
      <description>&lt;p&gt;A modern &lt;strong&gt;RSS 2.0&lt;/strong&gt; generator for PHP.&lt;/p&gt;</description>
      <category>PHP</category>
      <guid>https://pharaonic.dev/blog/php-rss-rebuilt</guid>
      <pubDate>Tue, 06 Oct 2026 10:00:00 +0300</pubDate>
    </item>
  </channel>
</rss>
```

### Adding Many Items

`addItems()` accepts any iterable of `Item` objects, so you can map your records directly:

```php
$feed->addItems(array_map(
    fn (array $post) => Item::make()
        ->title($post['title'])
        ->link($post['url'])
        ->guid($post['url'])
        ->publishedAt(new DateTimeImmutable($post['published_at'])),
    $posts
));
```

Items are written in the order you add them. Sort your records (usually newest first) before adding them.

### Pretty or Compact Output

`toXml()` indents with two spaces by default. Pass `false` for a compact document:

```php
$feed->toXml();      // indented, easy to read
$feed->toXml(false); // compact, smallest size
```

### Rules Worth Knowing

- **Empty values are omitted.** Passing `null` or `''` to an optional setter removes the element from the output. Values such as `"0"` are kept.
- **Order doesn't matter.** Required fields are validated when you call `toXml()`, so you can call setters in any order.
- **Escaping is automatic.** Text is XML-escaped for you. HTML in `description()` is escaped, which is how RSS 2.0 carries HTML. Use [`content:encoded`](#extensions) to send it as CDATA instead.
- **Dates keep their timezone.** Any `DateTimeInterface` is formatted as RFC 822 using the offset of the date you pass, never the server timezone.
- **No HTTP side effects.** The package never calls `header()` or `echo`.

:::warning Content-Type
Send `application/rss+xml; charset=UTF-8` (or `application/xml`) yourself. Browsers and readers may not recognize the feed if it's served as `text/html`.
:::

## Channel

`Feed` represents the RSS `<channel>`. It covers every channel element in RSS 2.0, and the writer outputs them in specification order whatever order you call the setters in.

### Required Elements

```php
use Pharaonic\RSS\Feed;

$feed = Feed::make()
    ->title('Pharaonic')                                  // <title>
    ->link('https://pharaonic.dev')                       // <link>
    ->description('Rooted in History. Engineering the Future.'); // <description>
```

`toXml()` throws an `InvalidFeedException` if any of the three is missing or blank.

### Text Elements

```php
$feed
    ->language('ar-EG')
    ->copyright('© Pharaonic')
    ->managingEditor('editor@pharaonic.dev (Editorial Team)')
    ->webMaster('webmaster@pharaonic.dev (Pharaonic Ops)')
    ->generator('My CMS')
    ->docs('https://www.rssboard.org/rss-specification')
    ->rating('(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l by "webmaster@example.com" on "2026.10.06T10:00-0500" r (n 0 s 0 v 0 l 0))');
```

:::info No implicit values
The package doesn't add a `<generator>` or a default `<pubDate>`. Only what you set is written.
:::

### Dates

`publishedAt()` writes `<pubDate>` and `lastBuildAt()` writes `<lastBuildDate>`. Both accept any `DateTimeInterface` and keep its timezone offset:

```php
$feed
    ->publishedAt(new DateTimeImmutable('2026-10-06 10:00:00', new DateTimeZone('UTC')))
    ->lastBuildAt(new DateTime('2026-10-06 13:00:00', new DateTimeZone('Africa/Cairo')));

// <pubDate>Tue, 06 Oct 2026 10:00:00 +0000</pubDate>
// <lastBuildDate>Tue, 06 Oct 2026 13:00:00 +0300</lastBuildDate>
```

Mutable `DateTime` objects are copied, so changing them afterwards doesn't change the feed. Pass `null` to remove a date.

### Categories

`category()` adds a category each time you call it. Pass a string, or a `Category` with a `domain`:

```php
use Pharaonic\RSS\Elements\Category;

$feed
    ->category('Technology')
    ->category(Category::make('Software/PHP')->domain('https://pharaonic.dev/topics'));
```

### Image

The channel image is an `Image` object. When you don't set its title or link, the writer uses the channel title and link, as RSS 2.0 recommends.

```php
use Pharaonic\RSS\Elements\Image;

$feed->image(
    Image::make('https://pharaonic.dev/logo.png')
        ->width(144)       // 1 to 144 (Image::MAX_WIDTH)
        ->height(144)      // 1 to 400 (Image::MAX_HEIGHT)
        ->description('Pharaonic logo')
);
```

Width and height are only written when set. Readers assume 88×31 when they're missing.

### Caching Hints

```php
use Pharaonic\RSS\Elements\Day;

$feed
    ->ttl(60)                 // readers may cache for 60 minutes
    ->skipHour(0)             // 0-23, GMT
    ->skipHour(1)
    ->skipDay(Day::SATURDAY)
    ->skipDay(Day::SUNDAY);
```

Duplicate hours and days are ignored. A negative `ttl`, an hour outside 0–23, or an unknown day name throws an `InvalidFeedException`.

### Cloud and Text Input

These two elements are rarely used, but both are supported:

```php
use Pharaonic\RSS\Elements\Cloud;
use Pharaonic\RSS\Elements\TextInput;
use Pharaonic\RSS\Elements\CloudProtocol;

$feed
    ->cloud(Cloud::make('rpc.pharaonic.dev', 443, '/rpc', 'pleaseNotify', CloudProtocol::XML_RPC))
    ->textInput(TextInput::make('Search', 'Search the blog', 'q', 'https://pharaonic.dev/search'));
```

`CloudProtocol` offers `XML_RPC`, `SOAP`, and `HTTP_POST`. The register procedure may be an empty string with `HTTP_POST`.

### Channel Extensions

Namespaced elements such as an Atom self link are attached with `extension()`. See [Extensions](#extensions).

```php
use Pharaonic\RSS\Extensions\Atom\Link;

$feed->extension(Link::self('https://pharaonic.dev/rss.xml'));
```

## Items

`Item` represents an RSS `<item>`. Every element is optional, but an item needs at least a title or a description.

### A Complete Item

```php
use Pharaonic\RSS\Elements\Enclosure;
use Pharaonic\RSS\Elements\Source;
use Pharaonic\RSS\Item;

$item = Item::make()
    ->title('PHP RSS rebuilt')
    ->link('https://pharaonic.dev/blog/php-rss-rebuilt')
    ->description('<p>A modern <strong>RSS 2.0</strong> generator for PHP.</p>')
    ->author('raggi@pharaonic.dev (Moamen Eltouny)')
    ->category('PHP')
    ->category('RSS')
    ->comments('https://pharaonic.dev/blog/php-rss-rebuilt#comments')
    ->enclosure(Enclosure::make('https://cdn.pharaonic.dev/cover.jpg', 48213, 'image/jpeg'))
    ->guid('https://pharaonic.dev/blog/php-rss-rebuilt')
    ->publishedAt(new DateTimeImmutable('2026-10-06 10:00:00'))
    ->source(Source::make('Pharaonic News', 'https://pharaonic.dev/news/rss.xml'));

$feed->addItem($item);
```

### Description and HTML

`description()` accepts HTML and escapes it in the output, which RSS readers decode and render. To ship the full article body as CDATA, add a [`content:encoded`](#extensions) extension alongside a short description.

### Author

RSS 2.0 expects an email address in `<author>`, conventionally `email (Name)`. If you only have a name, use the Dublin Core `Creator` extension instead:

```php
use Pharaonic\RSS\Extensions\DublinCore\Creator;

$item->extension(Creator::make('Moamen Eltouny')); // <dc:creator>Moamen Eltouny</dc:creator>
```

### GUIDs

A GUID uniquely identifies an item, so readers don't show it twice. RSS 2.0 treats a GUID as a permalink unless `isPermaLink="false"` is set.

```php
$item->guid('https://pharaonic.dev/blog/42');      // <guid>https://pharaonic.dev/blog/42</guid>
$item->guid('post-42', false);                     // <guid isPermaLink="false">post-42</guid>
```

You can also pass a `Guid` object:

```php
use Pharaonic\RSS\Elements\Guid;

$item->guid(Guid::make('post-42')->permalink(false));
```

:::warning Guid object and flag
Passing a `Guid` object together with the second argument throws an `InvalidItemException`. Set the flag on the object with `permalink()` instead.
:::

### Enclosures

An enclosure attaches a media file. It needs the URL, the size in bytes, and the MIME type:

```php
$item->enclosure(Enclosure::make('https://cdn.pharaonic.dev/podcast/1.mp3', 24986239, 'audio/mpeg'));
```

RSS 2.0 allows one enclosure per item. Use [Media RSS](#extensions) when you need several media objects.

### Source

`source()` credits the channel an item was republished from:

```php
$item->source(Source::make('Pharaonic News', 'https://pharaonic.dev/news/rss.xml'));
// <source url="https://pharaonic.dev/news/rss.xml">Pharaonic News</source>
```

### Item Extensions

Namespaced elements are added with `extension()` and written after the core item elements, in the order you add them:

```php
use Pharaonic\RSS\Extensions\Content\Encoded;

$item
    ->extension(Creator::make('Moamen Eltouny'))
    ->extension(Encoded::make('<article><h1>PHP RSS</h1><p>Full body…</p></article>'));
```

## Extensions

RSS 2.0 is extended with XML namespaces. The package ships four of the most common ones. Attach them to the feed or to an item with `extension()`.

Before writing, the writer collects the namespace of every extension in the feed and its items, then declares each one **once** on the `<rss>` root. Only the namespaces you actually use are declared.

| Extension | Namespace prefix | Classes |
| --- | --- | --- |
| Atom | `atom` | `Pharaonic\RSS\Extensions\Atom\Link` |
| Content | `content` | `Pharaonic\RSS\Extensions\Content\Encoded` |
| Dublin Core | `dc` | `Pharaonic\RSS\Extensions\DublinCore\Creator` |
| Media RSS | `media` | `Pharaonic\RSS\Extensions\Media\Content`, `Thumbnail`, `Title`, `Description` |

### Atom Self Link

Feed validators recommend that a feed links to its own URL. `Link::self()` sets `rel="self"` and `type="application/rss+xml"` for you:

```php
use Pharaonic\RSS\Extensions\Atom\Link;

$feed->extension(Link::self('https://pharaonic.dev/rss.xml'));
// <atom:link href="https://pharaonic.dev/rss.xml" rel="self" type="application/rss+xml"/>
```

`Link::make()` builds any other Atom link, for example a WebSub hub:

```php
$feed->extension(Link::make('https://pubsubhubbub.appspot.com/')->rel('hub'));
```

`Link` also has `type()`, `hreflang()`, `title()`, and `length()`.

### Full Content (content:encoded)

`Encoded` carries the full HTML body of an item as CDATA, without escaping. A `]]>` inside the content is split safely across CDATA sections, so the document always stays valid.

```php
use Pharaonic\RSS\Extensions\Content\Encoded;

$item
    ->description('A short summary for list views.')
    ->extension(Encoded::make($post->html));
```

### Creator (dc:creator)

Unlike `<author>`, `dc:creator` accepts a plain name:

```php
use Pharaonic\RSS\Extensions\DublinCore\Creator;

$item->extension(Creator::make('Moamen Eltouny'));
```

### Media RSS

`Content` describes a media object, with optional nested title, description, and thumbnails:

```php
use Pharaonic\RSS\Extensions\Media\Content;
use Pharaonic\RSS\Extensions\Media\Description;
use Pharaonic\RSS\Extensions\Media\Thumbnail;
use Pharaonic\RSS\Extensions\Media\Title;

$item->extension(
    Content::make('https://cdn.pharaonic.dev/giza.mp4')
        ->type('video/mp4')
        ->medium(Content::MEDIUM_VIDEO)
        ->expression(Content::EXPRESSION_FULL)
        ->fileSize(52428800)
        ->duration(95)
        ->width(1920)
        ->height(1080)
        ->lang('en')
        ->isDefault()
        ->title(Title::make('Giza pyramids'))
        ->description(Description::make('<b>Drone</b> footage')->type(Description::TYPE_HTML))
        ->thumbnail(Thumbnail::make('https://cdn.pharaonic.dev/giza.jpg')->width(1200)->height(630))
);
```

A `Thumbnail` can also be attached directly to an item, which many readers use as the item's preview image:

```php
$item->extension(Thumbnail::make('https://cdn.pharaonic.dev/note.jpg'));
```

| Constant | Values |
| --- | --- |
| `Content::MEDIUM_*` | `IMAGE`, `AUDIO`, `VIDEO`, `DOCUMENT`, `EXECUTABLE` |
| `Content::EXPRESSION_*` | `SAMPLE`, `FULL`, `NONSTOP` |
| `Title::TYPE_*` / `Description::TYPE_*` | `PLAIN`, `HTML` |

An unknown medium, expression, or text type throws an `InvalidElementException`.

:::info Order of extensions
Extensions are written after the core elements of their parent (channel or item), in the order you added them.
:::

## Custom Extensions

Any namespace the package doesn't ship (iTunes, GeoRSS, Slash, your own) can be added by implementing `Pharaonic\RSS\Contracts\Extension`.

### The Contract

```php
interface Extension
{
    public function prefix(): string;          // e.g. "geo"
    public function namespaceUri(): string;    // e.g. "http://www.w3.org/2003/01/geo/wgs84_pos#"
    public function write(XMLWriter $writer): void;
}
```

`write()` receives the `XMLWriter` positioned inside the parent element. Write prefixed element names such as `geo:lat`, and don't declare the namespace yourself, because the writer declares it on the root.

### Writing Values Safely

`XMLWriter` copies invalid UTF-8 and XML control characters into the output as they are. Use the helpers in `Pharaonic\RSS\Writer\Xml` to keep the document well-formed:

| Helper | Writes |
| --- | --- |
| `Xml::writeElement($writer, $name, $value)` | An element with escaped text |
| `Xml::writeText($writer, $value, $context)` | Escaped text inside the open element |
| `Xml::writeAttribute($writer, $name, $value)` | An escaped attribute on the open element |
| `Xml::writeCdata($writer, $content)` | CDATA, splitting any `]]>` safely |

Each one throws an `InvalidElementException` instead of writing an invalid value.

To check a value without writing it:

| Helper | Returns |
| --- | --- |
| `Xml::isValidText($value)` | `true` when the value is valid UTF-8 with only XML 1.0 characters |
| `Xml::assertValidText($value, $context)` | Nothing; throws an `InvalidElementException` naming `$context` when the value is invalid |
| `Xml::isNcName($name)` | `true` when the name is a valid unprefixed XML name, usable as a prefix or local name |

### Example: GeoRSS Point

```php title="src/Rss/GeoPoint.php"
namespace App\Rss;

use Pharaonic\RSS\Contracts\Extension;
use Pharaonic\RSS\Writer\Xml;
use XMLWriter;

final class GeoPoint implements Extension
{
    public function __construct(private float $latitude, private float $longitude)
    {
    }

    public function prefix(): string
    {
        return 'geo';
    }

    public function namespaceUri(): string
    {
        return 'http://www.w3.org/2003/01/geo/wgs84_pos#';
    }

    public function write(XMLWriter $writer): void
    {
        Xml::writeElement($writer, 'geo:lat', (string) $this->latitude);
        Xml::writeElement($writer, 'geo:long', (string) $this->longitude);
    }
}
```

Attach it like any built-in extension:

```php
$item->extension(new GeoPoint(29.9792, 31.1342));
// <geo:lat>29.9792</geo:lat>
// <geo:long>31.1342</geo:long>
```

### Example: iTunes Podcast Tags

One extension class can write several elements. This one writes any set of iTunes tags:

```php title="src/Rss/Itunes.php"
namespace App\Rss;

use Pharaonic\RSS\Contracts\Extension;
use Pharaonic\RSS\Writer\Xml;
use XMLWriter;

final class Itunes implements Extension
{
    /** @param array<string, string> $tags e.g. ['author' => 'Pharaonic', 'explicit' => 'false'] */
    public function __construct(private array $tags)
    {
    }

    public function prefix(): string
    {
        return 'itunes';
    }

    public function namespaceUri(): string
    {
        return 'http://www.itunes.com/dtds/podcast-1.0.dtd';
    }

    public function write(XMLWriter $writer): void
    {
        foreach ($this->tags as $name => $value) {
            Xml::writeElement($writer, 'itunes:' . $name, $value);
        }
    }
}
```

### Namespace Rules

The writer validates namespaces with `NamespaceRegistry` before it writes anything:

- The prefix must be a valid XML name and can't be `xml` or `xmlns`.
- The URI can't be empty.
- One prefix can't be bound to two different URIs in the same feed. Registering the same prefix and URI twice is fine.

Breaking a rule throws an `InvalidElementException`.

## Validation and Errors

The package refuses to produce an invalid document. Value objects validate their input as soon as you create them, and `toXml()` validates the feed as a whole before it writes anything.

### Exception Hierarchy

Every exception extends `Pharaonic\RSS\Exceptions\RssException`, which extends `RuntimeException`, so one `catch` covers them all.

| Exception | Thrown when |
| --- | --- |
| `InvalidFeedException` | The channel is missing a title, link, or description, or gets a negative `ttl`, an hour outside 0–23, or an unknown skip day |
| `InvalidItemException` | An item has neither a title nor a description, or `guid()` gets a `Guid` object together with a permalink flag |
| `InvalidElementException` | An element or extension gets an empty required value, an out-of-range number, an unknown choice, an invalid namespace, or text that isn't valid XML |

### When Validation Runs

| Check | Runs at |
| --- | --- |
| Empty URL, value, or name in an element or extension | Construction (`make()` / `new`) |
| Numeric ranges, choices (`medium`, `protocol`, `width`…) | The setter call |
| Channel `title`, `link`, `description` | `toXml()` |
| Item title-or-description | `toXml()` |
| Namespace prefixes and conflicts | `toXml()` |
| Invalid UTF-8 and XML control characters | `toXml()` |

### Catching Errors

```php
use Pharaonic\RSS\Exceptions\RssException;

try {
    $xml = $feed->toXml();
} catch (RssException $e) {
    error_log($e->getMessage());
    // "The RSS item at position 3 requires at least a title or a description."
}
```

Messages name the element, the field, and the value received, for example:

```text title="Messages" no-copy
The RSS channel requires a non-empty title. Call Feed::title() before serializing.
The image width must be between 1 and 144, 300 given.
The cloud protocol must be one of [xml-rpc, soap, http-post], "https" given.
The value of <title> contains invalid UTF-8 or characters that are not allowed in XML 1.0.
The XML namespace prefix "media" is already bound to "http://search.yahoo.com/mrss/" and cannot also be bound to "https://example.com/media".
```

:::warning Untrusted text
Content copied from user input, legacy databases, or Word documents often contains control characters (such as `\x0B`) or broken UTF-8. Clean it before adding it to the feed, for example with `mb_convert_encoding($text, 'UTF-8', 'UTF-8')` and `preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $text)`.
:::

## Feed API

`Pharaonic\RSS\Feed` is a `final` class. Every setter returns the same `Feed` instance for chaining. Optional string setters treat `null` and `''` as "not set".

### Setters

| Method | Element | Notes |
| --- | --- | --- |
| `Feed::make()` | | Creates an empty feed |
| `title(?string $title)` | `<title>` | Required |
| `link(?string $link)` | `<link>` | Required |
| `description(?string $description)` | `<description>` | Required |
| `language(?string $language)` | `<language>` | e.g. `en-US`, `ar-EG` |
| `copyright(?string $copyright)` | `<copyright>` | |
| `managingEditor(?string $managingEditor)` | `<managingEditor>` | `email (Name)` |
| `webMaster(?string $webMaster)` | `<webMaster>` | `email (Name)` |
| `publishedAt(?DateTimeInterface $date)` | `<pubDate>` | RFC 822, keeps the offset |
| `lastBuildAt(?DateTimeInterface $date)` | `<lastBuildDate>` | RFC 822, keeps the offset |
| `category(Category\|string $category)` | `<category>` | Adds one per call |
| `generator(?string $generator)` | `<generator>` | Not set by default |
| `docs(?string $docs)` | `<docs>` | |
| `cloud(?Cloud $cloud)` | `<cloud>` | |
| `ttl(?int $minutes)` | `<ttl>` | Throws when negative |
| `image(?Image $image)` | `<image>` | |
| `rating(?string $rating)` | `<rating>` | PICS rating |
| `textInput(?TextInput $textInput)` | `<textInput>` | |
| `skipHour(int $hour)` | `<skipHours><hour>` | 0–23, duplicates ignored |
| `skipDay(string $day)` | `<skipDays><day>` | A `Day` constant, duplicates ignored |
| `addItem(Item $item)` | `<item>` | |
| `addItems(iterable $items)` | `<item>` | Any iterable of `Item` |
| `extension(Extension $extension)` | namespaced | Written after the core channel elements |

### Output

| Method | Description | Returns |
| --- | --- | --- |
| `toXml(bool $pretty = true)` | Validates and serializes the feed. `false` gives compact output | `string` |

`toXml()` is a shortcut for `(new RssWriter($pretty))->write($feed)`. You can use `Pharaonic\RSS\Writer\RssWriter` directly if you prefer to inject the writer.

### Getters

| Method | Returns |
| --- | --- |
| `getTitle()`, `getLink()`, `getDescription()` | `?string` |
| `getLanguage()`, `getCopyright()`, `getManagingEditor()`, `getWebMaster()` | `?string` |
| `getGenerator()`, `getDocs()`, `getRating()` | `?string` |
| `getPublishedAt()`, `getLastBuildAt()` | `?DateTimeImmutable` |
| `getCategories()` | `list<Category>` |
| `getCloud()` | `?Cloud` |
| `getTtl()` | `?int` |
| `getImage()` | `?Image` |
| `getTextInput()` | `?TextInput` |
| `getSkipHours()` | `list<int>` |
| `getSkipDays()` | `list<string>` |
| `getItems()` | `list<Item>` |
| `getExtensions()` | `list<Extension>` |

## Item API

`Pharaonic\RSS\Item` is a `final` class. Every setter returns the same `Item` instance for chaining. Optional string setters treat `null` and `''` as "not set".

### Setters

| Method | Element | Notes |
| --- | --- | --- |
| `Item::make()` | | Creates an empty item |
| `title(?string $title)` | `<title>` | Title or description is required |
| `link(?string $link)` | `<link>` | |
| `description(?string $description)` | `<description>` | HTML allowed, escaped in output |
| `author(?string $author)` | `<author>` | `email (Name)` |
| `category(Category\|string $category)` | `<category>` | Adds one per call |
| `comments(?string $comments)` | `<comments>` | URL of the comments page |
| `enclosure(?Enclosure $enclosure)` | `<enclosure>` | |
| `guid(Guid\|string\|null $guid, ?bool $isPermaLink = null)` | `<guid>` | A string is a permalink unless the flag is `false` |
| `publishedAt(?DateTimeInterface $date)` | `<pubDate>` | RFC 822, keeps the offset |
| `source(?Source $source)` | `<source>` | |
| `extension(Extension $extension)` | namespaced | Written after the core item elements |

### Getters

| Method | Returns |
| --- | --- |
| `getTitle()`, `getLink()`, `getDescription()`, `getAuthor()`, `getComments()` | `?string` |
| `getCategories()` | `list<Category>` |
| `getEnclosure()` | `?Enclosure` |
| `getGuid()` | `?Guid` |
| `getPublishedAt()` | `?DateTimeImmutable` |
| `getSource()` | `?Source` |
| `getExtensions()` | `list<Extension>` |

## Elements API

Structured elements are small `final` value objects. Each has a static `make()` with the same arguments as its constructor, and required values are validated on creation.

### Pharaonic\RSS\Elements

| Class | Create with | Setters | Getters |
| --- | --- | --- | --- |
| `Category` | `make(string $value)` | `domain(?string)` | `getValue()`, `getDomain()` |
| `Guid` | `make(string $value)` | `permalink(bool $isPermaLink = true)` | `getValue()`, `isPermaLink()` |
| `Enclosure` | `make(string $url, int $length, string $type)` | | `getUrl()`, `getLength()`, `getType()` |
| `Image` | `make(string $url)` | `title(?string)`, `link(?string)`, `width(?int)`, `height(?int)`, `description(?string)` | `getUrl()`, `getTitle()`, `getLink()`, `getWidth()`, `getHeight()`, `getDescription()` |
| `Source` | `make(string $title, string $url)` | | `getTitle()`, `getUrl()` |
| `Cloud` | `make(string $domain, int $port, string $path, string $registerProcedure, string $protocol)` | | `getDomain()`, `getPort()`, `getPath()`, `getRegisterProcedure()`, `getProtocol()` |
| `TextInput` | `make(string $title, string $description, string $name, string $link)` | | `getTitle()`, `getDescription()`, `getName()`, `getLink()` |

| Constraint | Rule |
| --- | --- |
| `Enclosure` length | `>= 0` bytes |
| `Image` width | 1 to `Image::MAX_WIDTH` (144) |
| `Image` height | 1 to `Image::MAX_HEIGHT` (400) |
| `Cloud` port | 1 to 65535 |
| `Cloud` protocol | A `CloudProtocol` constant |

### Pharaonic\RSS\Extensions

| Class | Create with | Setters |
| --- | --- | --- |
| `Atom\Link` | `make(string $href)`, `self(string $href)` | `rel()`, `type()`, `hreflang()`, `title()`, `length(?int)`; getters `getHref()`, `getRel()`, `getType()`, `getHreflang()`, `getTitle()`, `getLength()` |
| `Content\Encoded` | `make(string $content)` | Getter: `getContent()` |
| `DublinCore\Creator` | `make(string $name)` | Getter: `getName()` |
| `Media\Content` | `make(string $url)` | `fileSize()`, `type()`, `medium()`, `isDefault()`, `expression()`, `bitrate()`, `duration()`, `width()`, `height()`, `lang()`, `title(?Title)`, `description(?Description)`, `thumbnail(Thumbnail)`; getters `getUrl()`, `getFileSize()`, `getType()`, `getMedium()`, `getIsDefault()`, `getExpression()`, `getBitrate()`, `getDuration()`, `getWidth()`, `getHeight()`, `getLang()`, `getTitle()`, `getDescription()`, `getThumbnails()` |
| `Media\Thumbnail` | `make(string $url)` | `width()`, `height()`, `time(?string)`; getters `getUrl()`, `getWidth()`, `getHeight()`, `getTime()` |
| `Media\Title` | `make(string $text)` | `type(?string)`; getters `getText()`, `getType()` |
| `Media\Description` | `make(string $text)` | `type(?string)`; getters `getText()`, `getType()` |

Each extension namespace has an abstract base class exposing `PREFIX` and `NAMESPACE_URI` constants: `AtomExtension`, `ContentExtension`, `DublinCoreExtension`, and `MediaExtension`.

### Pharaonic\RSS\Elements Constants

| Class | Members |
| --- | --- |
| `Day` | `MONDAY` … `SUNDAY`, `all()`, `isValid(string $day)` |
| `CloudProtocol` | `XML_RPC`, `SOAP`, `HTTP_POST`, `all()`, `isValid(string $protocol)` |

### Pharaonic\RSS\Writer

| Class | Members |
| --- | --- |
| `RssWriter` | `__construct(bool $pretty = true)`, `write(Feed $feed): string` |
| `DateFormatter` | `format(DateTimeInterface $date)`, e.g. `"Tue, 06 Oct 2026 10:00:00 +0300"` |
| `Xml` | `isValidText()`, `assertValidText()`, `isNcName()`, `writeElement()`, `writeText()`, `writeAttribute()`, `writeCdata()` |
| `NamespaceRegistry` | `register(string $prefix, string $uri)`, `has(string $prefix)`, `all()` |

## Examples

Real-world feeds built with PHP RSS.

### 1. Blog Feed in a Laravel App

Build the feed in a small class, return it from a controller with the right `Content-Type`, and cache the XML.

- ===Feed Builder

  ```php title="app/Rss/BlogFeed.php"
  namespace App\Rss;

  use App\Models\Post;
  use Pharaonic\RSS\Extensions\Atom\Link;
  use Pharaonic\RSS\Extensions\Content\Encoded;
  use Pharaonic\RSS\Extensions\DublinCore\Creator;
  use Pharaonic\RSS\Feed;
  use Pharaonic\RSS\Item;

  final class BlogFeed
  {
      public function toXml(): string
      {
          $posts = Post::query()->published()->latest('published_at')->limit(20)->get();

          return Feed::make()
              ->title(config('app.name') . ' Blog')
              ->link(url('/blog'))
              ->description('News & releases from our team.')
              ->language(app()->getLocale())
              ->lastBuildAt($posts->first()?->updated_at)
              ->ttl(60)
              ->extension(Link::self(route('blog.rss')))
              ->addItems($posts->map(fn (Post $post) => Item::make()
                  ->title($post->title)
                  ->link(route('blog.show', $post))
                  ->description($post->excerpt)
                  ->guid(route('blog.show', $post))
                  ->publishedAt($post->published_at)
                  ->extension(Creator::make($post->author->name))
                  ->extension(Encoded::make($post->body_html))))
              ->toXml();
      }
  }
  ```

- ===Controller

  ```php title="app/Http/Controllers/BlogFeedController.php"
  namespace App\Http\Controllers;

  use App\Rss\BlogFeed;
  use Illuminate\Support\Facades\Cache;

  class BlogFeedController
  {
      public function __invoke(BlogFeed $feed)
      {
          $xml = Cache::remember('blog.rss', now()->addHour(), fn () => $feed->toXml());

          return response($xml, 200, ['Content-Type' => 'application/rss+xml; charset=UTF-8']);
      }
  }
  ```

- ===Route

  ```php title="routes/web.php"
  use App\Http\Controllers\BlogFeedController;

  Route::get('/blog/rss.xml', BlogFeedController::class)->name('blog.rss');
  ```

`$posts->map()` returns a Laravel collection, which `addItems()` accepts because it's iterable. `lastBuildAt(null)` is fine when there are no posts yet.

### 2. Podcast Feed

Each episode carries an `<enclosure>` for classic podcast apps and a `media:content` for richer readers.

```php title="podcast.php"
use Pharaonic\RSS\Elements\Enclosure;
use Pharaonic\RSS\Elements\Image;
use Pharaonic\RSS\Extensions\Atom\Link;
use Pharaonic\RSS\Extensions\DublinCore\Creator;
use Pharaonic\RSS\Extensions\Media\Content;
use Pharaonic\RSS\Extensions\Media\Thumbnail;
use Pharaonic\RSS\Feed;
use Pharaonic\RSS\Item;

$feed = Feed::make()
    ->title('Pharaonic Podcast')
    ->link('https://pharaonic.dev/podcast')
    ->description('Conversations about building software.')
    ->language('en')
    ->image(Image::make('https://cdn.pharaonic.dev/podcast/cover.png'))
    ->extension(Link::self('https://pharaonic.dev/podcast/rss.xml'));

foreach ($episodes as $episode) {
    $feed->addItem(
        Item::make()
            ->title(sprintf('Episode %d: %s', $episode->number, $episode->title))
            ->enclosure(Enclosure::make($episode->audioUrl, $episode->bytes, 'audio/mpeg'))
            ->guid('pharaonic-podcast-' . $episode->number, false)
            ->publishedAt($episode->publishedAt)
            ->extension(Creator::make('Pharaonic'))
            ->extension(
                Content::make($episode->audioUrl)
                    ->fileSize($episode->bytes)
                    ->type('audio/mpeg')
                    ->medium(Content::MEDIUM_AUDIO)
                    ->expression(Content::EXPRESSION_FULL)
                    ->duration($episode->seconds)
            )
            ->extension(Thumbnail::make($episode->coverUrl))
    );
}

file_put_contents(__DIR__ . '/public/podcast/rss.xml', $feed->toXml());
```

Episodes without a description are valid because each one has a title.

### 3. Static Feed Generated at Deploy Time

For static sites, write the feed to disk once per build, compact, so the web server can serve it directly.

```php title="bin/build-feed.php"
use Pharaonic\RSS\Exceptions\RssException;
use Pharaonic\RSS\Feed;
use Pharaonic\RSS\Item;

require __DIR__ . '/../vendor/autoload.php';

$pages = json_decode(file_get_contents(__DIR__ . '/../content/pages.json'), true);

$feed = Feed::make()
    ->title('Docs Changelog')
    ->link('https://docs.example.com')
    ->description('Every documentation update.')
    ->lastBuildAt(new DateTimeImmutable('now', new DateTimeZone('UTC')));

foreach ($pages as $page) {
    $feed->addItem(
        Item::make()
            ->title($page['title'])
            ->link($page['url'])
            ->guid($page['url'])
            ->publishedAt(new DateTimeImmutable($page['updated_at']))
    );
}

try {
    file_put_contents(__DIR__ . '/../public/feed.xml', $feed->toXml(false));
} catch (RssException $e) {
    fwrite(STDERR, 'Feed build failed: ' . $e->getMessage() . PHP_EOL);
    exit(1);
}
```

Failing the build on an `RssException` keeps an invalid feed from ever reaching readers.

### 4. Aggregated Feed with Sources

When you republish items from other feeds, credit each origin with `source()` and keep the original GUID.

```php title="aggregate.php"
use Pharaonic\RSS\Elements\Category;
use Pharaonic\RSS\Elements\Source;
use Pharaonic\RSS\Feed;
use Pharaonic\RSS\Item;

$feed = Feed::make()
    ->title('PHP Weekly Picks')
    ->link('https://picks.example.com')
    ->description('The best PHP articles from around the web.');

foreach ($picks as $pick) {
    $feed->addItem(
        Item::make()
            ->title($pick['title'])
            ->link($pick['link'])
            ->description($pick['summary'])
            ->category(Category::make($pick['topic'])->domain('https://picks.example.com/topics'))
            ->guid($pick['guid'], $pick['guid_is_url'])
            ->source(Source::make($pick['site_name'], $pick['site_feed_url']))
    );
}

echo $feed->toXml();
```

## Troubleshooting

### "The RSS channel requires a non-empty title"

The channel is missing one of its three required elements. Call `title()`, `link()`, and `description()` with non-blank values before `toXml()`. Whitespace-only values count as blank.

### "The RSS item at position N requires at least a title or a description"

The item at zero-based position `N` has neither. This often happens when a database column is `null`. Set at least one of them, or skip the record.

### "contains invalid UTF-8 or characters that are not allowed in XML 1.0"

The text contains broken UTF-8 or control characters such as `\x0B` or `\x1F`, usually from pasted or legacy content. XML 1.0 can't represent them, so the package refuses to write them. Clean the value before adding it:

```php
$clean = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', mb_convert_encoding($text, 'UTF-8', 'UTF-8'));
```

### HTML Shows as Escaped Tags in My Reader

`description()` escapes HTML (`&lt;p&gt;`), which is correct RSS 2.0, and readers decode it. Some readers prefer the full body as CDATA. Add `Encoded::make($html)` from `Pharaonic\RSS\Extensions\Content` alongside the description.

### The Browser Downloads or Shows the Feed as Text

The response is missing a proper `Content-Type`. The package never sends headers. Send `Content-Type: application/rss+xml; charset=UTF-8` from your application, and make sure nothing is printed before the XML declaration.

### Dates Show the Wrong Time

Dates are formatted with the timezone of the object you pass, never the server's. A `DateTimeImmutable` created without a timezone uses `date.timezone` from `php.ini`. Pass an explicit `DateTimeZone`, or call `->setTimezone()` before adding the date.

### Readers Show Duplicate Items

The item has no GUID, or its GUID changes between builds. Set a stable `guid()` for every item, such as the permalink or a database ID with `false` as the second argument.

### "already bound to … and cannot also be bound to …"

Two extensions use the same prefix with different namespace URIs, often a custom extension reusing `media`, `dc`, `content`, or `atom`. Give your custom extension a different prefix, or use the same URI as the built-in one.

### "Item::guid() received a Guid object and an isPermaLink flag"

You passed both a `Guid` object and the second argument. Use either `guid('id', false)` or `guid(Guid::make('id')->permalink(false))`.

### "Call to undefined method … setTitle()"

You're calling the 1.x API. Setters lost their `set` prefix and the classes were renamed. See [Upgrading from 1.x](#upgrade-guide).

## Upgrade Guide

Every release is listed with its changes in the [changelog](https://github.com/Pharaonic/php-rss/blob/8.6.x/CHANGELOG.md).

### From 8.5.1 to 8.6.0

8.6.0 removes the `Pharaonic\RSS\Support` namespace. Its classes moved, with the same names and members:

| 8.5.1 | 8.6.0 |
| --- | --- |
| `Pharaonic\RSS\Support\Day` | `Pharaonic\RSS\Elements\Day` |
| `Pharaonic\RSS\Support\CloudProtocol` | `Pharaonic\RSS\Elements\CloudProtocol` |
| `Pharaonic\RSS\Support\Xml` | `Pharaonic\RSS\Writer\Xml` |
| `Pharaonic\RSS\Support\NamespaceRegistry` | `Pharaonic\RSS\Writer\NamespaceRegistry` |
| `Pharaonic\RSS\Support\DateFormatter` | `Pharaonic\RSS\Writer\DateFormatter` |

There are no aliases for the old names, so update your imports. Custom extensions that use `Support\Xml` need `use Pharaonic\RSS\Writer\Xml;`. Behavior is unchanged.

### From 8.0.0 to 8.0.1

8.0.1 restored the 1.x root namespace. Replace `Pharaonic\Rss\` with `Pharaonic\RSS\` in your imports.

### From 1.x

The package was rebuilt from scratch. The old `RSS` and `RSSItem` classes are gone and there is no compatibility layer, but most feeds migrate in a few minutes.

#### Class and Method Map

| 1.x | Current |
| --- | --- |
| `Pharaonic\RSS\RSS` | `Pharaonic\RSS\Feed` |
| `Pharaonic\RSS\RSSItem` | `Pharaonic\RSS\Item` |
| `new RSS()` | `Feed::make()` |
| `new RSSItem()` | `Item::make()` |
| `setTitle()`, `setDescription()`, `setLink()` | `title()`, `description()`, `link()` |
| `setLanguage()`, `setCopyright()` | `language()`, `copyright()` |
| `RSS::setPublished(string)` | `Feed::publishedAt(DateTimeInterface)` |
| `RSS::setUpdated(string)` | `Feed::lastBuildAt(DateTimeInterface)` |
| `RSS::setImage($url, $width, $height)` | `Feed::image(Image::make($url)->width($width)->height($height))` |
| `RSS::setItem($item)` | `Feed::addItem($item)` |
| `RSSItem::appendToChannel($rss)` | `$feed->addItem($item)` |
| `RSSItem::setGUID(string)` | `Item::guid(string, ?bool $isPermaLink)` |
| `RSSItem::setAuthor()` | `Item::author()` |
| `RSSItem::setCategory()` | `Item::category()` |
| `RSSItem::setPublished(string)` | `Item::publishedAt(DateTimeInterface)` |
| `RSS::render()` / `(string) $rss` | `Feed::toXml()` |

#### Before and After

- ===1.x

  ```php title="1.x" no-copy
  use Pharaonic\RSS\RSS;
  use Pharaonic\RSS\RSSItem;

  $rss = new RSS();
  $rss->setTitle('Pharaonic')
      ->setDescription('Rooted in History. Engineering the Future.')
      ->setLink('https://pharaonic.dev')
      ->setImage('https://pharaonic.dev/logo.png')
      ->setPublished(date('r'));

  (new RSSItem())
      ->setTitle('PHP RSS rebuilt')
      ->setDescription('A modern RSS 2.0 generator for PHP.')
      ->setLink('https://pharaonic.dev/packages/php/rss')
      ->setGUID('php-rss-rebuild')
      ->setPublished(date('r'))
      ->appendToChannel($rss);

  echo $rss->render(); // also sent a Content-Type header
  ```

- ===Current

  ```php title="Current"
  use Pharaonic\RSS\Elements\Image;
  use Pharaonic\RSS\Feed;
  use Pharaonic\RSS\Item;

  $feed = Feed::make()
      ->title('Pharaonic')
      ->description('Rooted in History. Engineering the Future.')
      ->link('https://pharaonic.dev')
      ->image(Image::make('https://pharaonic.dev/logo.png'))
      ->publishedAt(new DateTimeImmutable());

  $feed->addItem(
      Item::make()
          ->title('PHP RSS rebuilt')
          ->description('A modern RSS 2.0 generator for PHP.')
          ->link('https://pharaonic.dev/packages/php/rss')
          ->guid('php-rss-rebuild', false)
          ->publishedAt(new DateTimeImmutable())
  );

  header('Content-Type: application/rss+xml; charset=UTF-8');
  echo $feed->toXml();
  ```

#### Behavior Changes to Review

- **No HTTP headers.** `render()` sent `Content-Type: text/xml`. `toXml()` only returns a string, so send the header from your application.
- **No implicit values.** 1.x always wrote a `<generator>` and defaulted `<pubDate>` to the current time. Call `generator()` and `publishedAt()` if you need them.
- **Image size.** 1.x always wrote width 88 and height 31. They're now only written when set, and readers apply the same defaults.
- **GUIDs.** `guid('id', false)` writes `isPermaLink="false"` for identifiers that aren't URLs. `guid('https://…')` keeps the old meaning.
- **Item validation.** An item now needs only a title or a description. A link is no longer required.
- **Exceptions.** Errors extend `Pharaonic\RSS\Exceptions\RssException` instead of a generic `\Exception`.
- **Element order.** Channel elements follow RSS 2.0 specification order, so the output differs from 1.x even for identical content.
