Pages

Friday, December 24, 2010

XML Sorting using attributes - PHP

////////function for convert xml attributes into array/////////

function create_array($obj){
$arr = (array)$obj;
if(empty($arr)){
$arr = "";
} else {
foreach($arr as $key=>$value){
if(!is_scalar($value)){
$arr[$key] = create_array($value);
}
}
}
return $arr;
}

////////function for sort xml/////////

function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}

$xml = simplexml_load_file("sort.xml") or die ("Unable to load XML file!");

$temp = "";
foreach($test as $file)
{
$arr = create_array($file->attributes());
$arr = $arr['@attributes'];
$temp[] = $arr;
}

////////function for sort xml $temp=array() and second field for key for sorting/////////
$final = subval_sort($temp,'sort');

echo "
";
print_r($final);
echo "
";

?>

sample xml


 <?xml version="1.0" encoding="utf-8"?>
<gallery path="video">
<item thumbnail="" title = "" vid="" sort="1" />
<item thumbnail="" title = "" vid="" sort="2" />
<item thumbnail="" title = "" vid="" sort="3" />
<item thumbnail="" title = "" vid="" sort="4" />
<item thumbnail="" title = "" vid="" sort="5" />
<item thumbnail="" title = "" vid="" sort="6" />
</gallery>

No comments: