Tuesday 17 July 2018

Generating a Dynamic XML or Text Playlist using PHP

Generating a Dynamic XML or Text Playlist using PHP

If you’ve ever tried to incorporate some kind of Flash music player into your website, you’ll probably notice that it will more than likely contain an option to use a playlist to play multiple songs in sequence. This can work really well if you’ve got a set number of songs that you want to play, not so great however if the songs are constantly changing, coming from a database or are user-contributed.
If this is the case then a standard XML or text file won’t do. Instead I show you below how to use PHP to generate this playlist on-the-fly.
The Solution
For the example below I’ll presume that the playlist is in XML format. Let’s look at the part where we embed the flash player and reference the playlist:

  1. <param name="FlashVars" value="...&playlist=http://www.mydomain.com/playlist.php&..." />  
Notice how we reference a PHP file? Let’s take a look at what this playlist.php file might look like. Depending on what you are trying to achieve this will no doubt change. In the example below I’m going to get the latest 5 songs from a MySQL table:

  1. // specify that the output will be xml  
  2. header("Content-Type: text/xml");  
  3.   
  4. // establish a connection to the MySQL database  
  5. $conn = mysql_connect("localhost""user""pass");  
  6. $db = mysql_select_db("song_database");  
  7.   
  8. echo '<?xml version="1.0" encoding="UTF-8" ?> 
  9. <songs>';  
  10.   
  11. // get 5 latest songs  
  12. $query = "SELECT `filename` FROM `songs` ORDER BY `dateAdded` DESC LIMIT 5";  
  13. $result = mysql_query($query);  
  14. while ($row=mysql_fetch_assoc($result)) {  
  15.     echo '<song>'.$row['filename'].'</song>';  
  16. }  
  17.   
  18. echo '</songs>';  
So there we have it. If a song was to get added, the playlist would update automatically without having to manually change the static playlist file.
Some Considerations
Caching
Flash has a tendancy to cache files that it uses which, as a result means the dynamic playlist being included might not update automatically. If this is a problem for you, one way to get around this would be to add a changing parameter to the end of the filename like so:

  1. <param name="FlashVars" value="playlist=http://www.mydomain.com/playlist.php%3F<?php echo time(); ?>" />  
PHP files not accepted as playlist FlashVar
Some music players specify that the playlist being used cannot be anything but a certain filetype. In the case of the XML playlist above we would get an error using playlist.php even though the final output is actually XML. To solve this scenario you can add a rule to your .htaccess file like so:
  1. Redirect /playlist.xml http://www.mydomain.com/playlist.php  
Then simply use playlist.xml in the FlashVar and (fingers crossed) the PHP playlist should be referenced instead.

0 comments:

Post a Comment