PHP Sort XML Elements by Date -
below xml file
<?xml version="1.0"?> <calender> <task> <date>00/00/0000</date> <title>my birthday</title> <description>today birthday!</description> </task> <task> <date>04/08/2013</date> <title>test</title> <description>swdefswde</description> </task> <task> <date>04/02/2013</date> <title>test</title> <description>test</description> </task> <task> <date>04/01/2013</date> <title>egfwe</title> <description>wefwef</description> </task> <task> <date>04/03/2013</date> <title>ssdv</title> <description>ssdvs</description> </task> </calender>
i'm trying add them array, , resort elements date [then rewrite xml file sorted xml]. can please me?
i have tired following code doesnt work [cant add them array]
$xml_temp = array(); foreach ($xml_add->task $atask) { $xml_temp[] = $atask; } print_r ($xml_temp);
your array fine. next thing need usort
:
$xml=simplexml_load_string(<<<xml <?xml version="1.0"?> <calender> <task> <date>00/00/0000</date> <title>my birthday</title> <description>today birthday!</description> </task> <task> <date>04/08/2013</date> <title>test</title> <description>swdefswde</description> </task> <task> <date>04/02/2013</date> <title>test</title> <description>test</description> </task> <task> <date>04/01/2013</date> <title>egfwe</title> <description>wefwef</description> </task> <task> <date>04/03/2013</date> <title>ssdv</title> <description>ssdvs</description> </task> </calender> xml ); $arr=array(); foreach($xml->task $atask) { $arr[]=$atask; } //print_r($arr); /* uncomment above line debug */ usort($arr,function($a,$b){ return strtotime($a->date)-strtotime($b->date); }); //print_r($arr); /* uncomment above line debug */ $xml=simplexml_load_string(<<<xml <?xml version="1.0"?> <calender> </calender> xml ); foreach($arr $atask) { $ttask=$xml->addchild($atask->getname()); $ttask->addchild($atask->date->getname(),(string)$atask->date); $ttask->addchild($atask->title->getname(),(string)$atask->title); $ttask->addchild($atask->description->getname(),(string)$atask->description); } echo $xml->asxml();
the echoed xml (manually formatting make nicer):
<?xml version="1.0"?> <calender> <task> <date>00/00/0000</date> <title>my birthday</title> <description>today birthday!</description> </task> <task> <date>04/01/2013</date> <title>egfwe</title> <description>wefwef</description> </task> <task> <date>04/02/2013</date> <title>test</title> <description>test</description> </task> <task> <date>04/03/2013</date> <title>ssdv</title> <description>ssdvs</description> </task> <task> <date>04/08/2013</date> <title>test</title> <description>swdefswde</description> </task> </calender>
requires php >= 5.3
Comments
Post a Comment