I wanted to add a blog to a new website (this website already has a Mastodon account) and after a few minutes of searching for options I realised “Wait, why don't I just use Mastodon?”
Turns out it only took a handful of lines of code:
$url = "https://glasgow.social/@neil.rss"; $data = file_get_contents($filename); $posts = new SimpleXmlElement($data); echo "<ul>"; foreach($posts->channel->item as $p) { echo "<li><strong><a target='new' href='{$p->link}'>{$p->title}</a></strong><br />"; echo $p->description; echo "</li>"; } echo "</ul>";
Done. I can just insert that in any part of a website to show all the comments made by my mastodon account.
If I want to show only certain comments (e.g. those with a #blog hashtag) I can add some extra code inside the foreach (this is a little convulted as I wanted to ignore case)
$allowed_post = false; foreach($p->category as $hash_tag) { if(strtolower($hash_tag) == "blog") $allowed_post = true; } if(!$allowed_post) continue;
I'll add some caching to prevent hitting the Mastodon server's RSS file too often.
$url = "https://glasgow.social/@neil.rss"; $basename = basename($url); $cache_file = "cache/$basename"; if(!file_exists($cache_file)) { $data = file_get_contents($url); file_put_contents($cache_file, $data); } else { $cache_ts = filemtime($cache_file); if($cache_ts >= strtotime("-5 minutes")) { $data = file_get_contents($cache_file); } else { $data = file_get_contents($url); file_put_contents($cache_file, $data); } } $posts = new SimpleXmlElement($data); echo "<ul>"; foreach($posts->channel->item as $p) { $allowed_post = false; foreach($p->category as $hash_tag) { if(strtolower($hash_tag) == "glasgow") $allowed_post = true; } if(!$allowed_post) continue; echo "<li><strong><a target='new' href='{$p->link}'>{$p->title}</a></strong><br />"; echo $p->description; echo "</li>"; } echo "</ul>";