Wednesday, January 2, 2008

Directory listing as podcast

Here is a quick and dirty (as always) php script to turn a directory listing into an rss 2.0 feed with enclosures, suitable for use with a podcast client. Just drop a copy of this script into the directory and point your feed reader at it. The script automatically hides itself in the listing.

PHP:
<?php
$link = 'http://'.$_SERVER['SERVER_NAME'].preg_replace('/\/[^\/]+\.[^\/]+$/', '/', $_SERVER['REQUEST_URI']);
$items = preg_replace('/\s+->\s.*$/','', explode("\n", `ls -FlopTt`));

$items = preg_grep('/('.preg_replace('/.*\//', '', $_SERVER['PHP_SELF']).')$|^$|^total/', $items, PREG_GREP_INVERT);

header('Content-type: application/rss+xml; charset=utf-8');
echo '<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>'.$_SERVER['SERVER_NAME'].preg_replace('/\/[^\/]+\.[^\/]+$/', '/', $_SERVER['REQUEST_URI']).'</title>
<link>'.$link.'</link>
<description>Contents of '.$link.'</description>
<language>en-us</language>
';
foreach ($items as $value) echo '<item>
<title>'.preg_replace('/^(\S+\s+){10}/', '', $value).'</title>
<description>'.$value.'</description>
<enclosure url="'.$link.rawurlencode(preg_replace('/^(\S+\s+){10}/', '', $value)).'" length="'.preg_replace('/^(\S+\s+){5}((\S+){1}).*/', '\2', $value).'" type="'.mime_content_type(preg_replace('/^(\S+\s+){10}/', '', $value)).'" />
<guid>'.$link.rawurlencode(preg_replace('/^(\S+\s+){10}/', '', $value)).'</guid>
<pubDate>'.gmdate('D, d M Y G:i:s', strtotime(preg_replace('/^(\S+\s+){6}((\S+\s+){4}).*/', '\2', $value))).' GMT</pubDate>
</item>
';
echo '</channel>
</rss>';
?>