Objective: To be able to include updated items from an RSS feed on a JSP-based site without Java/JSP based support for inclusion of RSS content.
Solution: A PHP script that would could be referenced externally to generate JavaScript array items based on the Open-Source MagpieRSS project.
Technologies Used: PHP, JavaScript
rss2js.php
An external PHP script that generates arrays of JavaScript variables for data from an RSS feed.
<?php
header("Content-Type: text/javascript");
define('MAGPIE_DIR', './php/magpierss/');
require_once(MAGPIE_DIR.'rss_fetch.inc');
$url=$_GET['url'];
echo "var rssitemtitle=new Array();\n";
echo "var rssitemhref=new Array();\n";
echo "var rssitemdesc=new Array();\n\n";
$count=0;
// multiple dashes to be replaced with emdash
$dashes = Array();
$dashes[] = "---";
$dashes[] = "--";
if($url){
$rss = fetch_rss($url);
foreach ($rss->items as $item) {
$href = trim($item['link']);
$title = strip_tags(trim($item['title']));
$title = str_replace($dashes,"—",$title);
// escape single quotes to prevent JS errors
$title = str_replace("'","\'",$title);
$description = strip_tags(trim($item['description']));
$description = str_replace($dashes,"—",$description);
// escape single quotes to prevent JS errors
$description = str_replace("'","\'",$description);
// only display the first three sentences of the item.
$parts=explode(".",$description);
$description = $parts[0].". ".$parts[1].". ".$parts[2].".";
echo "rssitemtitle[$count]='".$title."';\n";
echo "rssitemhref[$count]='$href';\n";
echo "rssitemdesc[$count]='".$description."';\n\n";
$count++;
}
}else{
echo "alert('no URL specified!')";
}
?>
Implementation
This script is referenced in the <head> section of the HTML document as an external JavaScript library with the URL of the feed to be converted passed to the script as a query string variable.
<script type="text/javascript"
src="rss2js.php?url=http://wrnrfan.com/feed/">
</script>
Once the script is called custom JavaScript can be written to use the information as the developer sees fit.