1

I have a little problem with the usage of SimpleDOM and sortedXPath. Given is the following XML Structure. I want to sort it either by row id, name or birthday.

<table>
  <data>
    <row id="1">
      <column>Jimmy</column>
      <column>01/10/1977</column>
     </row>
     <row id="3">
       <column>Johnny</column>
       <column>04/01/2001</column>
     </row>
     <row id="2">
       <column>Tim</column>
       <column>13/02/1990</column>
     </row>
     <row id="4">
       <column>Paul</column>
       <column>13/02/1955</column>
     </row>
   </data>
</table>

Sorting by id turned out to be simple by using:

foreach($xmlObject->data->sortedXPath('row','@id', SORT_DESC) as $node)

so $node contains all rows and i can output them in the correct order. But i'm unable to order by name or date. I have tried:

foreach($xmlObject->data->sortedXPath('row','column[0]', SORT_DESC) as $node)
foreach($xmlObject->data->sortedXPath('row/column[0]','.', SORT_ASC) as $node)

but this creates either $nodes with just the value of column and in a strange oder or no output at all. Please help i'm stuck here for hours now :(

Regards

Cabal
  • 11
  • 1

1 Answers1

1

XPath counts 1-based.

foreach($xmlObject->data->sortedXPath('row','column[1]', SORT_DESC) as $node)
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Hm OK that works for name. But the date is more or less a random result regardless of the sort direction. – Cabal Jun 04 '11 at 16:32
  • @Cabal: Sure, because your date is DD/MM/YYYY, and quite unsurprisingly that doesn't sort in any meaningful way. – Tomalak Jun 04 '11 at 16:58
  • sortedXPath can handle multiple atributes. When I split up the date into year, month, day and sort one at a time it should work. Sadly sortedXPath doesnt like php functions as input something like this would be great foreach($xmlObject->data->sortedXPath('row',substr('column[2]', -4), SORT_DESC, substr('column[2]', -7, 2), SORT_DESC, substr('column[2]', -10, 2), SORT_DESC, ) as $node) – Cabal Jun 04 '11 at 18:26
  • @Cabal: You could try XPath functions instead. `$xmlObject->data->sortedXPath('row', 'concat(substring(column[2], 7, 4),substring(column[2], 4, 2),substring(column[2], 1, 2))')` but I somehow doubt that this will work. In any case, simply reformatting your XML to YYYY/MM/DD should work better, as this sorts naturally. – Tomalak Jun 04 '11 at 18:38
  • @Tomalak: You are right it doesnt work. Unfortunately changing the format of the date is not an option. Strange is that substring has no effect at all foreach($xmlObject->data->sortedXPath('row','substring(column[2], 7, 4)', SORT_DESC) as $node) should at least sort by year. But even this is not working. – Cabal Jun 04 '11 at 20:08
  • @Cabal: Consider sorting the nodes yourself, instead of trying to get this to work. – Tomalak Jun 04 '11 at 21:09
  • @Tomalak: I did. Using usort now its a compact and much simpler way. Thanks for your support. – Cabal Jun 05 '11 at 10:19