3

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 want to sort is:

<?xml version="1.0" encoding="UTF-8"?>
<cursos>
  <curso>
    <id>DRW</id>
    <nome>Design Responsivo</nome>
    <categoria>Web</categoria>
    <inicio>30/02/2013</inicio>
    <periodo>Sábados de manhã</periodo>
    <cargaHoraria>40h</cargaHoraria>
    <objetivos></objetivos>
  </curso>
  <curso>
    <id>MSQ</id>
    <nome>MySQL</nome>
    <categoria>Banco de dados</categoria>
    <inicio>30/03/2013</inicio>
    <periodo>Sábados de manhã</periodo>
    <cargaHoraria>20h</cargaHoraria>
    <objetivos></objetivos>
  </curso>
  <curso>
    <id>MBY</id>
    <nome>Iniciação à informática</nome>
    <categoria>Iniciantes e Usuários Av.</categoria>
    <inicio>30/04/2013</inicio>
    <periodo>Matutino 1</periodo>
    <cargaHoraria>80h</cargaHoraria>
    <objetivos></objetivos>
  </curso>
  <curso>
    <id>FCS</id>
    <nome>Desenvolvendo em C#</nome>
    <categoria>Desenvolvimento</categoria>
    <inicio>14/04/2013</inicio>
    <periodo>Domingo</periodo>
    <cargaHoraria>60h</cargaHoraria>
    <objetivos></objetivos>
  </curso>
  <curso>
    <id>MAY</id>
    <nome>Modelagem em Maya</nome>
    <categoria>Artes gráficas</categoria>
    <inicio>13/04/2013</inicio>
    <periodo>Sábado 08h:00-13h:00</periodo>
    <cargaHoraria>60h</cargaHoraria>
    <objetivos></objetivos>
  </curso>
</cursos>

I found this and this solution, but the logic to apply this on multidimensional XML array is not clearly for me. Can someone help me?

Thanks in advance.

Community
  • 1
  • 1
Guilherme Oderdenge
  • 4,935
  • 6
  • 61
  • 96

1 Answers1

2

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>';
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • +1 Though I would recommend not putting it back together as a string. This is better: http://stackoverflow.com/a/3361590/18771 – Tomalak Apr 01 '13 at 17:06