Output XML using PHP from MySQL database

Firstly, Let me talk about this post. If your advance level php programmer, this is a piece of cake for you. I would like to say this post for beginner level. It would be a little difficult for a beginner. You may need xml output when you want to integrate with flash and MySQL records such as photo gallery, playlist for flash mp3 player, RSS Feeds, and so on.

I would like to show you an example to create xml playlist. So you can use this in flash mp3 player like JW Player. I have created songs table in my database. songs_id, album_id, songs_title and songs_link fields are included in this table.

In PHP file :


<?php
 header('Content-type: text/xml');
 $db_host = "localhost" ; // MySQL Host
 $db_user = "root" ;    // Database Username
 $db_password = "" ; // Database Password
 $db_name = "music" ; // Database Name

 $db_link = mysql_connect("$db_host","$db_user","$db_password");
 mysql_select_db($db_name, $db_link);

?>
 <playlist version="1" xmlns="http://xspf.org/ns/0/">
 <trackList>
 <?php
 $album_id = $_GET[aid];
 $songs = "SELECT * From songs WHERE album_id='$album_id' ORDER BY song_title ASC";
 $songs_list = mysql_query( $songs, $db_link );
 $songs_total = mysql_num_rows( $songs_list );
 if( $songs_total == 0 )    {    exit;    }
 for( $f = 0; $f < $songs_total; $f++ )
 {
 $each = mysql_fetch_assoc( $songs_list );
 ?>
 <track>
 <title><?=$each['song_title']?></title>
 <location>http://www.yourdomain.com/<?=$each['song_link']?></location>
 </track>
 <?php

 } // End of loop

 ?>
 </trackList>
 </playlist>

Then you can use call this file with album id like xml.php?aid=10.

Download Source ( size 745 B)

Related Posts


Leave Your Response

* Name, Email, Comment are Required

Categories