I was looking at some flash mp3 streaming players and the thing i noticed was you had to add each .mp3 directory and title to the playlist.xml file... Can php loop all the mp3 files in a directory and place the titles and path in a .xml file and place the .xml file in a specific directory on your server...

something like this.... every new mp3 to server and it generates the code needed for playlist.xml

<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns = "http://xspf.org/ns/0/">
  <trackList>

<track>
  <location>mp3/demo.mp3</location>
  <title>MP3 Player!</title>
  <creator>E-Phonic</creator>
</track>

<track>
  <location>mp3/mymp3.mp3</location>
  <title>My song 1</title>
  <creator>Me</creator>
</track>

<track>
  <location>http://www.mywebsite.com/mp3files/mymp3.mp3</location>
  <title>My song 2</title>
  <creator>Me</creator>
</track>

</trackList>
</playlist>

    Hi,

    I think it may help you:

    1) Open an XML file in write mode using FILE OPERATIONS. If not exists, then create it.
    2) Read directory from where you want filenames to add to xml file.
    3) Write it to an XML file.
    4) Copy/Move XML file to new directory.

    Thanks

      Example, using XMLWriter:

      $data = array(array('mp3/demo.mp3', 'MP3 Player!', 'E-Phonic'),
                    array('mp3/mymp3.mp3', 'My song 1', 'Me'),
                    array('http://www.example.com/mp3files/mymp3.mp3', 'My song 2', 'Me'));
      
      $xmlw = new XMLWriter;
      $xmlw->openMemory();
      $xmlw->setIndentString('  ');
      $xmlw->setIndent(true);
      $xmlw->startDocument();
      $xmlw->startElement('playList');
      $xmlw->writeAttribute('version', '1');
      $xmlw->writeAttribute('xmlns', 'http://xspf.org/ns/0/');
      $xmlw->startElement('trackList');
      foreach ($data as $track) {
          $xmlw->startElement('track');
          $xmlw->writeElement('location', $track[0]);
          $xmlw->writeElement('title', $track[1]);
          $xmlw->writeElement('creator', $track[2]);
          $xmlw->endElement();
      }
      $xmlw->endElement();
      $xmlw->endElement();
      $xmlw->endDocument();
      $doc = $xmlw->flush();
      file_put_contents('path/to/file', $doc);
      
      echo '<pre>';
      echo htmlspecialchars($doc);
      echo '</pre>';

      Output:

      <?xml version="1.0"?>
      <playList version="1" xmlns="http://xspf.org/ns/0/">
        <trackList>
          <track>
            <title>MP3 Player!</title>
            <location>mp3/demo.mp3</location>
            <creator>E-Phonic</creator>
          </track>
          <track>
            <title>My song 1</title>
            <location>mp3/mymp3.mp3</location>
            <creator>Me</creator>
          </track>
          <track>
            <title>My song 2</title>
            <location>http://www.example.com/mp3files/mymp3.mp3</location>
            <creator>Me</creator>
          </track>
        </trackList>
      </playList>

        Ty for that example because I went to go research what you told me and there were no examples really... Only question I have with your coding is would that loop through all the MP3s i have and auto write them...

        in the bold does that go to a directory www.example.com/mp3files/ then loop through the directory fetching all the mp3s... So i would not have to write each location manually... Thanks for this awesome example...

        Also just so I know this is what this will do.... I would put this php page up... Have a button that once pushed will generate a .xml coded file (of a mp3 playlist) and place it into a directory of my chosing?

        $data = array(array('mp3/demo.mp3', 'MP3 Player!', 'E-Phonic'),
        array('mp3/mymp3.mp3', 'My song 1', 'Me'),
        array('http://www.example.com/mp3files/mymp3.mp3', 'My song 2', 'Me'));

                       
        $xmlw = new XMLWriter; $xmlw->openMemory(); $xmlw->setIndentString(' '); $xmlw->setIndent(true); $xmlw->startDocument(); $xmlw->startElement('playList'); $xmlw->writeAttribute('version', '1'); $xmlw->writeAttribute('xmlns', 'http://xspf.org/ns/0/'); $xmlw->startElement('trackList'); foreach ($data as $track) { $xmlw->startElement('track'); $xmlw->writeElement('location', $track[0]); $xmlw->writeElement('title', $track[1]); $xmlw->writeElement('creator', $track[2]); $xmlw->endElement(); } $xmlw->endElement(); $xmlw->endElement(); $xmlw->endDocument(); $doc = $xmlw->flush(); file_put_contents('path/to/file', $doc); echo '<pre>'; echo htmlspecialchars($doc); echo '</pre>';

          The code uses a hand-coded array for input just for example, but putting the data into an array like that or similar would be easiest.

          Your sample data looks to me more like what would be retrieved from a database, but you say you'd get it from directory listings. You wouldn't get a value like "http://example.com/song.mp3" from a directory listing, nor any of the other values, like those under "title" and "creator". And how you would go about assembling the data depends on where it comes from.

          As for "a button that once pushed will generate a .xml coded file": Yes, that's somewhat the idea. The script would be invoked, like any script, upon suitable input, whether from a "submit" button, http request, command line, or however you want to invoke it.

          The line containing "file_put_contents()" puts the xml file into a disk file. You'd just need to change the pathname appropriately. And, btw, did you run the script? It should run as-is and show you its results.

          If you post more specific information about your input data and how you retrieve it, I'll give some more help if you need it.

            ok awesome... Actually it wouldnt read from a database... but using I think function mime_content_type($filename) to search through all the .mp3's... Listing them in that bold area... The directory would be ./music/

            In the mean time I have done this coding (altering) which works but has nothing to do with a FULL mp3 flash music player.... But a single flash player per a song, plus the ability to download the song and file size of song.... BTW I still would like to know how to get this code you have done working right (for what i would like to see)...

            Here is the code for single flash mini players per a song...

            require("dbconn.php");
            
            echo "<script type=\"text/javascript\" src=\"swfobject.js\"></script>";
            
            if(!function_exists('mime_content_type')) {
            
            function mime_content_type($filename) {
            
                $mime_types = array(
            
                    'txt' => 'text/plain',
                    'htm' => 'text/html',
                    'html' => 'text/html',
                    'php' => 'text/html',
                    'css' => 'text/css',
                    'js' => 'application/javascript',
                    'json' => 'application/json',
                    'xml' => 'application/xml',
                    'swf' => 'application/x-shockwave-flash',
                    'flv' => 'video/x-flv',
            
                    // images
                    'png' => 'image/png',
                    'jpe' => 'image/jpeg',
                    'jpeg' => 'image/jpeg',
                    'jpg' => 'image/jpeg',
                    'gif' => 'image/gif',
                    'bmp' => 'image/bmp',
                    'ico' => 'image/vnd.microsoft.icon',
                    'tiff' => 'image/tiff',
                    'tif' => 'image/tiff',
                    'svg' => 'image/svg+xml',
                    'svgz' => 'image/svg+xml',
            
                    // archives
                    'zip' => 'application/zip',
                    'rar' => 'application/x-rar-compressed',
                    'exe' => 'application/x-msdownload',
                    'msi' => 'application/x-msdownload',
                    'cab' => 'application/vnd.ms-cab-compressed',
            
                    // audio/video
            		'wma' => 'audio/ x-ms-wma',
                    'mp3' => 'audio/mpeg',
                    'qt' => 'video/quicktime',
                    'mov' => 'video/quicktime',
            
                    // adobe
                    'pdf' => 'application/pdf',
                    'psd' => 'image/vnd.adobe.photoshop',
                    'ai' => 'application/postscript',
                    'eps' => 'application/postscript',
                    'ps' => 'application/postscript',
            
                    // ms office
                    'doc' => 'application/msword',
                    'rtf' => 'application/rtf',
                    'xls' => 'application/vnd.ms-excel',
                    'ppt' => 'application/vnd.ms-powerpoint',
            
                    // open office
                    'odt' => 'application/vnd.oasis.opendocument.text',
                    'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
                );
            
                $ext = strtolower(array_pop(explode('.',$filename)));
                if (array_key_exists($ext, $mime_types)) {
                    return $mime_types[$ext];
                }
                elseif (function_exists('finfo_open')) {
                    $finfo = finfo_open(FILEINFO_MIME);
                    $mimetype = finfo_file($finfo, $filename);
                    finfo_close($finfo);
                    return $mimetype;
                }
                else {
                    return 'application/octet-stream';
                }
            }
            }
            
            
            function mb($s){
            	$size=filesize($s)/1024/1024;
            return (round($size,1)." Mb");
            }
            
            
            function trimmer( $a )
            {
            	$arr = array( '.wma','.mp3', '.',  '[_quote2_mark_]', '[_and_]', '[_quote_mark_]','_');
            	$arr2 = array( ''   ,''    , '.',  '"'             , '&',       "'" , ' ');
            
            	return( ucwords( str_replace( $arr,$arr2 , $a ) ) );
            }
            
            function f_dir( $kvtnev )
            {
            
            $kvt = opendir( $kvtnev );
            while ( gettype( $fajl = readdir( $kvt ) ) !== "boolean" ) {
            
            		/* if this is a folder*/
            		if ( is_dir( "$kvtnev/$fajl" ) AND $fajl != '.' AND $fajl != '..' )
            		{
            		if($fajl==".." OR $fajl==".")
            continue;
            $rexp_string_filter["csb"]="^[A-Z ][__]*$";
            $check=ereg($rexp_string_filter["csb"], $fajl);
            
            
            			if(!$check)
            			{
            				$newfilename="";
            				$newfilename=str_replace(" ","_",$fajl);
            				$newfilename=str_replace("__","",$newfilename);
            				$newfilename=strtolower($newfilename);
            				rename($kvtnev."/".$fajl , $kvtnev."/".$newfilename) or die("Could not rename the file:".$fajl);
            				$fajl=$newfilename;
            			}
            
            
            			print '<blockquote><table border="1" bordercolor="#000000" width="485">
              <tbody>';
            
            
            			print  "\r
            	<tr>
            				<td width=\"485\" bgcolor=\"#0000CC\"><div align=\"left\" class=\"gypsybody style8\">
            				<div align=\"center\"><span class=\"style1\"><strong>".trimmer($fajl)."</strong></span></div>
            </div></td>
            	</tr>
            ";
            
            			f_files("$kvtnev/$fajl");
            
            			print '
              </tbody>
            </table></blockquote>';
            
            		}
            
            
            	}
            	closedir( $kvt );
            }
            
            function f_files( $kvtnev )
            	{
            print '<table width="485" bgcolor="#999999">';
            			print "\r
            			<tr>
                <td width=\"75\" bgcolor=\"#000099\"><div align=\"center\" class=\"gypsybody style1\">Streaming</div></td>
                <td width=\"284\" bgcolor=\"#000099\"><div align=\"center\"><span class=\"gypsybody style1\">Title Of Song -</span> <span class=\"gypsybody style2\">click to download </span></div></td>
                <td width=\"110\" bgcolor=\"#000099\"><div align=\"center\"><span class=\"gypsybody style1\">File Size </span></div></td>
              </tr>";
            
            
            		$color1 = "#cccccc";
            		$color2 = "#FFFFFF";
            		$row_count = 0;
            
            		$kvt = opendir( $kvtnev );
            		while ( gettype( $fajl = readdir( $kvt ) ) !== "boolean" )
            		{
            
            			if($fajl==".." OR $fajl==".")
            			continue;
            			$rexp_string_filter["csb"]="^[A-Z ]*$";
            			$check=ereg($rexp_string_filter["csb"], $fajl);
            
            			if (!$check) //if it has capital letters, or spaces
            			{
            				$newfilename="";
            				$newfilename=str_replace(" ","_",$fajl);
            				$newfilename=str_replace("__","",$newfilename);
            				$newfilename=str_replace("'","[_quote_mark_]",$newfilename);
            				$newfilename=str_replace('&',"[_and_]",$newfilename);
            				$newfilename=str_replace('"','[_quote2_mark_]' ,$newfilename);
            				$newfilename=strtolower($newfilename);
            
            				rename($kvtnev."/".$fajl , $kvtnev."/".$newfilename) or die("Could not rename the file:".$fajl);
            				$fajl=$newfilename;
            			}
            
            
            			if ( mime_content_type( "$kvtnev/$fajl" )=="audio/mpeg"  OR mime_content_type( "$kvtnev/$fajl" )=="audio/ x-ms-wma" )
            			{
            
            				$url = htmlspecialchars( "$kvtnev/$fajl" );
            
            
            				$row_color = ($row_count % 2) ? $color1 : $color2;
            
            				// print "==== $fajl<br>";
            				print "\r
            	<tr>
            	    <td width=\"75\" bgcolor=\"$row_color\"><div align=\"center\" class=\"gypsybody\"><div id=\"$fajl\">
              This text will be replaced by the flash music player.
            </div>
            
            <script type=\"text/javascript\">
               var so = new SWFObject(\"playerMini.swf\", \"mymovie\", \"75\", \"30\", \"7\", \"#FFFFFF\");
               so.addVariable(\"autoPlay\", \"no\");
               so.addVariable(\"soundPath\", \"$url\");
               so.write(\"$fajl\");
            </script></div></td>
            			<td width=\"284\" bgcolor=\"$row_color\"><div align=\"left\" class=\"gypsybody\">
            			<div align=\"center\"><a href=\"$url\" class=\"gypsybody style15\">".trimmer($fajl)."</a></div>
            			</div></td>
            			<td width=\"110\" bgcolor=\"$row_color\"><div align=\"left\" class=\"gypsybody\">
            			<div align=\"center\">". mb("$kvtnev/$fajl"). "</div>
            			</div></td>
            		</tr>";
            					$row_count++;
            				}
            
            		}
            
            	}
            
            
            
            print '<style type="text/css">
            		<!--
            		.style1 {color: #FFFFFF}
            		-->
            		</style>';
            
            f_dir( "music");

              I'm totally at a loss; most of what you said and the code you posted seems to me to be, at best, only remotely connected with your original post. Plus, reading code "formattted" like that makes my eyes hurt. So I'm just sticking with your original question.

              Since you didn't or won't tell us where you're getting the data you want in the xml from, I've written a script (below) that will find mp3 files in a directory and read their id3 tags into an array. Then it constructs the xml document and writes it to disk. I've tested it; it works, writing each mp3 filepath as "location", the title tag as "title", and the artist tag as "creator", in exactly the same way as in your original post (as the code I posted earlier does).

              The "get_tags()" function is adopted from a class method I wrote quite awhile ago. The only hang-up with it is that it uses "exec()" on an Windows executable (Tag.exe) that you would need to download and put in your path. The only place I can find to download it from anymore is here. (There are a couple of PEAR mp3 id packages you could alternatively use if you're not using Windows, as is probably the case. But at least the make_xml_doc() function will work.)

              Good luck.

              $music_dir   = './music/';     // Put the pathname of your music directory here.
              $output_file = './music.xml';  // Put the pathname of where you want to put the xml file here.
              
              $mp3_files = glob($music_dir . '*.mp3');
              foreach ($mp3_files as $each) {
                  $info[] = get_tags($each);
              }
              $xml = make_xml_doc($info);
              file_put_contents($output_file, $xml); 
              
              // These three lines for devlopment. Remove for production.
              echo '<pre>';
              echo htmlspecialchars(file_get_contents($output_file));
              echo '</pre>';
              
              function make_xml_doc($data)
              {
                  $xmlw = new XMLWriter; 
                  $xmlw->openMemory(); 
                  $xmlw->setIndentString('  '); 
                  $xmlw->setIndent(true); 
                  $xmlw->startDocument(); 
                  $xmlw->startElement('playList'); 
                  $xmlw->writeAttribute('version', '1'); 
                  $xmlw->writeAttribute('xmlns', 'http://xspf.org/ns/0/'); 
                  $xmlw->startElement('trackList'); 
                  foreach ($data as $track) { 
                      $xmlw->startElement('track'); 
                      $xmlw->writeElement('location', $track['location']); 
                      $xmlw->writeElement('title', $track['title']); 
                      $xmlw->writeElement('creator', $track['creator']); 
                      $xmlw->endElement(); 
                  } 
                  $xmlw->endElement(); 
                  $xmlw->endElement(); 
                  $xmlw->endDocument(); 
                  $doc = $xmlw->flush();
                  return $doc;
              } 
              
              function get_tags($file, $tags = array('title', 'artist'))
              {
                  $cmd_str = 'Tag "' . $file . '" 2>&1';
                  $ret = exec($cmd_str, $output);
                  $arr = array();
                  $arr['location'] = $file;
                  foreach ($tags as $tag) {
                      $found = false;
                      foreach ($output as $line) {
                          if (stripos($line, $tag) === 0) {
                              $pos = strpos($line, ':');
                              if ($tag == 'artist') {
                                  $tag = 'creator';
                              }
                              $arr[$tag] = trim(strip_tags(substr($line, $pos + 1)));
                              $found = true;
                              break;
                          }
                      }
                      if (!$found) {
                          $arr[$tag] = '-not present-';
                      }
                  }
                  return $arr;
              }

                Yes I was afraid that posting or even showing you what i was doing in the mean while would just do more confusion than any good. My apologizes... As what you have written is awesome and exactly what I was asking for in the original place. Thank you for helping me with this...

                  Hi,

                  I have one query.
                  In this case, XML file is recreated every time new File is uploaded.
                  If admin uploads playlist, then recreating an XML file is not a problem as there is only one user and there will be no deadlock condition.

                  But Suppose, there are two registered users who have privilege to upload playlist. One user is uploading playlist, and other one is viewing. Something like deadlock condition happens..

                  Then how are we going to generate XML file?

                  Thanks

                    I think (so take this with a grain of salt) that the best solution is to dynamically generate XML documents, or any format of varying data, from data stored in a database using concurrency controls. Then the XML would be constructed from query results and sent directly in the response. Frequently-requested sets of data could be stored as XML doc files (or separate db tables) by, for example, a cron job.

                    To more specifically answer your question: I think that using flock() will solve the problem in all but the most extreme cases. But for more, and probably better, ideas start a new thread. 🙂

                      Thanks for giving idea.

                      I have never used flock() in php and concurrency controls in MYSQL.
                      Can you give example for this.

                      Thanks in advance.

                        4 days later

                        Or if you can't install any XML-generating libraries, just write to any file in the format of an XML document, use \t for a tab, \r for carriage return and \n for a new line in the file.

                          5 months later

                          I LOVE the code that Installer provided, but there's one thing I can't work out with XMLWriter - how do you specify the start or duration? The XML is a little different than what the rest of this code does, and I can't seem to produce the meta tag that is necessary:

                          Using this from the above examples:

                          $xmlw->startElement('meta');
                          $xmlw->writeAttribute('rel','start');
                          $xmlw->writeElement('meta','10');
                          $xmlw->endElement();
                          

                          Yields This:

                          <meta rel="start">
                          <meta>10</meta>
                          </meta>
                          

                          But I need this:

                          <meta rel="start">10</meta>
                          

                          I can't seem to figure out the correct sequence of XMLWriter steps to make this happen! 😕 Any help is appreciated!

                            7 months later
                            Installer;10899755 wrote:

                            ........
                            Since you didn't or won't tell us where you're getting the data you want in the xml from, I've written a script (below) that will find mp3 files in a directory and read their id3 tags into an array. Then it constructs the xml document and writes it to disk. I've tested it; it works, writing each mp3 filepath as "location", the title tag as "title", and the artist tag as "creator", in exactly the same way as in your original post (as the code I posted earlier does)..........

                            I'm barely a coder, never done php - just actionscript. This was incredibly helpful thanks!

                              A pity I didn't see this sooner...

                              gdpodesta;10918925 wrote:

                              I can't seem to produce the meta tag that is necessary:...

                              <meta rel="start">10</meta>
                              

                              The "10" is just text. Start the <meta> element; set its rel= attribute; $xmlw->text('10'); and end the element.

                                Write a Reply...