PHP Sort XML Elements by Date

后端 未结 2 1840
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 10:09

Below is my XML file





00/00/0000
My Birthday
         


        
2条回答
  •  一个人的身影
    2020-12-20 11:06

    Your array is fine. The next thing you need is usort:

    $xml=simplexml_load_string(<<
    
    
    
    00/00/0000
    My Birthday
    Today is my birthday!
    
    
    
    04/08/2013
    test
    swdefswde
    
    
    
    04/02/2013
    test
    test
    
    
    
    04/01/2013
    egfwe
    wefwef
    
    
    
    04/03/2013
    ssdv
    ssdvs
    
    
    
    XML
    );
    $arr=array();
    foreach($xml->task as $aTask)
    {
        $arr[]=$aTask;
    }
    //print_r($arr);
    /* uncomment the above line to debug */
    usort($arr,function($a,$b){
        return strtotime($a->date)-strtotime($b->date);
    });
    //print_r($arr);
    /* uncomment the above line to debug */
    $xml=simplexml_load_string(<<
    
    
    XML
    );
    foreach($arr as $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 to make it look nicer):

    
    
    
    
    00/00/0000
    My Birthday
    Today is my birthday!
    
    
    
    04/01/2013
    egfwe
    wefwef
    
    
    
    04/02/2013
    test
    test
    
    
    
    04/03/2013
    ssdv
    ssdvs
    
    
    
    04/08/2013
    test
    swdefswde
    
    
    
    

    Requires PHP >= 5.3

    Live demo

提交回复
热议问题