Skip to content

Instantly share code, notes, and snippets.

@chrillep
Created September 24, 2024 08:00
Show Gist options
  • Save chrillep/2ba52d41058e21178306923ffb0e380b to your computer and use it in GitHub Desktop.
Save chrillep/2ba52d41058e21178306923ffb0e380b to your computer and use it in GitHub Desktop.
FeedServiceProvider for custom xml and json feed (acorn, wordpress, laravel)
<?php
declare(strict_types=1);
namespace App\Providers;
use DOMDocument;
use Illuminate\Support\ServiceProvider;
class FeedServiceProvider extends ServiceProvider
{
/**
* Register assets services.
*/
#[\Override]
public function register(): void
{
parent::register();
add_action(
hook_name: 'init',
callback: $this->addCustomFeed(...),
priority: 10,
accepted_args: 2
);
add_filter(
hook_name: 'feed_content_type',
callback: $this->customFeedContentType(...),
priority: 10,
accepted_args: 2
);
}
public function addCustomFeed(): void
{
add_feed('customJson', $this->renderCustomJsonFeed(...));
add_feed('customXml', $this->renderCustomXmlFeed(...));
}
public function customFeedContentType($content_type, $type): string
{
return match ($type) {
'customJson' => 'application/json',
'customXml' => 'application/rss+xml',
default => $content_type,
};
}
public function renderCustomJsonFeed(): void
{
$feedItems = collect(
get_posts(
[
'post_type' => 'post',
'posts_per_page' => 10,
]
)
);
echo $feedItems->toJson();
}
public function renderCustomXmlFeed(): void
{
$feedItems = collect(
get_posts([
'post_type' => 'post',
'posts_per_page' => 10,
])
);
$dom = new DOMDocument('1.0', 'UTF-8');
$rss = $dom->createElement('rss');
$rss->setAttribute('version', '2.0');
$channel = $dom->createElement('channel');
foreach ($feedItems as $item) {
$title = $dom->createElement('title', htmlspecialchars($item->post_title));
$link = $dom->createElement('link', get_permalink($item->ID));
$description = $dom->createElement('description', htmlspecialchars($item->post_excerpt));
$itemElement = $dom->createElement('item');
$itemElement->appendChild($title);
$itemElement->appendChild($link);
$itemElement->appendChild($description);
$channel->appendChild($itemElement);
}
$rss->appendChild($channel);
$dom->appendChild($rss);
echo $dom->saveXML();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment