Skip to content

Instantly share code, notes, and snippets.

@m-manu
Last active December 23, 2015 19:49
Show Gist options
  • Save m-manu/6685355 to your computer and use it in GitHub Desktop.
Save m-manu/6685355 to your computer and use it in GitHub Desktop.
Script to convert an RSS feed string to clean, cross-browser HTML string (Output will be XHTML compliant if the feed source is XHTML compliant)
<?php
/**
* Converts an RSS feed string to clean, cross-browser HTML string
* (Output will be XHTML compliant if the feed source is XHTML compliant)
* @param string $rss_feed_xml_str RSS feed (XML) string
* @return string HTML string on success, <b>false</b> on failure.
*/
function rss_to_html($rss_feed_xml_str) {
$feed_html = false;
$feed = simplexml_load_string($rss_feed_xml_str, null, LIBXML_NOCDATA);
if ($feed) {
$channel = $feed->channel;
$feed_html = sprintf('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%s</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="description" content="%s"/>
<style type="text/css">
.pubdate {
font-size: small;
}
dd {
margin-bottom: 30px;
}
description {
}
</style>
</head>
<body>
<div id="rss_to_html">
<h1><a href="%s">%s</a></h1>
%s
<dl>
', htmlspecialchars($channel->title), htmlspecialchars($channel->description), htmlspecialchars($channel->link), htmlspecialchars($channel->title), htmlspecialchars($channel->description));
foreach ($channel->item as $item) {
$feed_html .= sprintf('
<dt><a href="%s">%s</a></dt>
<dd>
<div class="pubdate">%s</div>
<div class="description">%s</div>
', htmlspecialchars($item->link), $item->title, $item->pubDate, $item->description);
if (isset($item->category)) {
$feed_html .= "Categories: <strong>" . implode('</strong>, <strong>', (array) $item->category) . "</strong>\n</dd>\n";
}
if (isset($item->enclosure, $item->enclosure['url'])) {
if (strpos($item->enclosure['type'], 'image') !== false) {
$feed_html .= sprintf("<img src=\"%s\" alt=\"preview\"/>\n", htmlspecialchars($item->enclosure['url']));
}
}
if (isset($item->source)) {
if (isset($item->source['url'])) {
$feed_html .= sprintf("<div>Source: <a href=\"%s\">%s</a></div>\n", htmlspecialchars($item->source['url']), htmlspecialchars($item->source));
}
else {
$feed_html .= sprintf("<div>Source: %s</div>\n", htmlspecialchars($item->source));
}
}
$feed_html .= "</dd>\n";
}
$feed_html .= "</dl>\n</div>\n</body>\n</html>\n";
}
else {
error_log("Could not parse input RSS feed XML");
}
return $feed_html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment