How to sort SimpleXMLElement on PHP

后端 未结 1 1496
一生所求
一生所求 2021-01-21 12:07

I want to know how can I sort simple XML elements with PHP. Yes, I found some threads that address the same subject — but I couldn\'t solve my problem.

The XML what I wa

相关标签:
1条回答
  • 2021-01-21 12:30

    There's no real easy way to sort using SimpleXML; you would have to create an array with the elements, sort them and then reconstruct the XML:

    $d = simplexml_load_string($xml);
    // turn into array
    $e = array();
    foreach ($d->curso as $curso) {
            $e[] = $curso;
    }
    // sort the array
    usort($e, function($a, $b) {
            return $a->cargaHoraria - $b->cargaHoraria;
    });
    // put it back together
    echo '<cursos>';
    foreach ($e as $node) {
            echo $node->saveXML();
    }
    echo '</cursos>';
    
    0 讨论(0)
提交回复
热议问题