<?php function iTunesXmlParser($filename, $sort_field=NULL, $sort_direction="up")
{
// save the input in global variables for the sort function
global $g_ITX_field, $g_ITX_direction;
$g_ITX_field = $sort_field;
$g_ITX_direction = $sort_direction;
// init main variables
$songs = array();
$xml = NULL; // parsed XML
// read the file into $xml first
ob_start();
readfile($filename);
$xml = ob_get_contents();
ob_end_clean();
// open the xml document in the DOM
if (!$xml || !$dom = domxml_open_mem($xml))
die("Could not parse iTunes XML file: ".$filename);
// get the root element
$root = $dom->document_element();
// yeah "dict" means everything, playlist, and song that makes sense... NOT
// find the first "dict"
$children = $root->child_nodes();
foreach ($children as $child)
{
if ($child->node_name()=="dict")
{
$root = $child;
break;
}
}
// do that again, and find the second inner dict
$children = $root->child_nodes();
foreach ($children as $child)
{
if ($child->node_name()=="dict")
{
$root = $child;
break;
}
}
// now go through all the child elements
$children = $root->child_nodes();
foreach ($children as $child)
{
// all the sub dicts from here on should be songs
if ($child->node_name()=="dict")
{
$song = NULL;
// get all the elements
$elements = $child->child_nodes();
for ($i = 0; $i<count($elements); $i++)
{
// alright whomever wrote this xml file was smoking something serious
// in normal XML documents we would do:
// <artist>Daft Punk</artist>
// but in Apple iTunes bong land we do:
// <key>Artist</key><string>Daft Punk</string>
if ($elements[$i]->node_name()=="key")
{
// so I'm just going to expect that i++ (<string>, <int>, etc...) is always going to be there,
// if the key's name is <key>
// instead of doing some error checking here to make sure there are matching values to keys
$key = $elements[$i]->get_content();
$i++;
$value = $elements[$i]->get_content();
$song[$key]=$value;
}
}
// save the song
if ($song)
$songs[] = $song;
}
}
// now sort the songs
// $sort_field=NULL, $sort_direction="up"
if ($sort_field)
{
uasort($songs, "iTunesXmlSongSort");
}
return $songs;
}
$g_ITX_field = NULL;
$g_ITX_direction = NULL;
// to be used with the uasort() array function in PHP
function iTunesXmlSongSort($left, $right)
{
global $g_ITX_field, $g_ITX_direction;
// return the strcmp() of the two fields
if (isset($left[$g_ITX_field])&&isset($right[$g_ITX_field]))
{
if (strcasecmp($g_ITX_direction, "up"))
return strcasecmp($left[$g_ITX_field],$right[$g_ITX_field]);
else
return strcasecmp($right[$g_ITX_field],$left[$g_ITX_field]);
}
elseif (isset($left[$g_ITX_field]))
return -1;
else
return 1;
}
?>