PDA

View Full Version : Random File list with PHP



jonahholliday
November 29th, 2006, 04:28 PM
Hi,

I have been scratching my head trying to figure this out... sadly I haven't. I'm sure this is something simple; please help me out.

using PHP I would like to list all the files in a specified folder in a random sequence. And output this as an xml file. Here's what I have so far...


<?
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

echo "<songs>\n";
/////////////////////////////////////////////////////////////////////////////////////

$file_dir="mp3";
////////////////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////////////////


$dir=opendir($file_dir);
while ($file=readdir($dir))
{
if ($file != "." && $file != "..")

{
list($name, $ext) = explode(".", $file);
list($artist, $title) = explode("-", $name);

echo "<song path=\"".$file."\" artist=\"".$artist."\" title= \"".$title."\"></song>\n ";

}
}

echo "</songs>\n";
?>

How can I modify this to generate a random list.

Thanks!

bwh2
November 29th, 2006, 04:41 PM
within your while, array_push the files into an array. then pull random ones out of the array.

jonahholliday
November 29th, 2006, 04:47 PM
how would I actually code that? I haven't used array_push before...

Thanks!

bwh2
November 30th, 2006, 11:50 AM
i also made the code a little cleaner.

<?
/* directory to go through */
$file_dir = 'mp3';

/* temporary storage for the filenames */
$files = array();

/* open directory */
$dir = opendir($file_dir);

/* loop through directory */
while ( $file = readdir($dir) )
{
if ($file != '.' && $file != '..')
{
/* push into array of files */
array_push( $files, $file );
}
}

/* shuffle the order of filenames in the array */
shuffle( $files );

/* print beginning of XML doc */
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
echo '<songs>'."\n";

/* loop through files */
foreach( $files as $file ) {
list($name, $ext) = explode('.', $file);
list($artist, $title) = explode('-', $name);
echo "\t".'<song path="'.$file.'" artist="'.$artist.'" title="'.$title.'"></song>'."\n";
}

/* close XML file */
echo '</songs>'."\n";
?>

jonahholliday
November 30th, 2006, 01:36 PM
You Rock!!!

bwh2
November 30th, 2006, 02:08 PM
thanks.