Parsing multiple XML feeds with PHP into a single sorted array

I want to create a sorted list that looks something like

  • $ VAR1 [0], $ VAR2 [0] ...
  • $ VAR1 [1], $ VAR2 [1] ...

The data comes from several identical structured XML files:

$xmlfile="
<Level1>
 <Level2>
  <Level2Item VAR1="1" VAR2="2" ... />
  <Level2Item VAR1="4" VAR2="5" ... />
  <Level2Item VAR1="7" VAR2="8" ... />
 </Level2>
</Level1>";

//Extract each item
$xml = new SimpleXMLElement($xmlfile);
foreach ($xml->Level2[0] as $result) {
 array_push($VAR1Array, $result['VAR1']);
 array_push($VAR2Array, $result['VAR2']);
 //... etc etc
}
//sort
//$sortedArray = sort($VAR1Array);

Exit

Array(
  [0] => SimpleXMLElement Object([0] => 1)
  [1] => SimpleXMLElement Object([0] => 4)
  [2] => SimpleXMLElement Object([0] => 7)
)

From this XML structure, what's the best way to store data in a single array? I want to collect all the data in one array so that I can sort it by one or two VARs and display the results.

+3
source share
4 answers

I'm not quite sure what sorting you are trying to do (you should specify with some examples). But optimally, you will not load XML fragments into your array.

$xmlfile="
<Level1>
 <Level2>
  <Level2Item VAR1="1" VAR2="2" ... />
  <Level2Item VAR1="4" VAR2="5" ... />
  <Level2Item VAR1="7" VAR2="8" ... />
 </Level2>
</Level1>";

//Extract each item
$xml = new SimpleXMLElement($xmlfile);
foreach ($xml->Level2[0] as $result) {
 $VAR1Array[] = (int) $result['VAR1'];
 $VAR2Array[] = (int) $result['VAR2'];
 //... etc etc
}

, sort() , (.. sort($array); , $array . int like php, , . array_push , php $var[] .

+2

, , $xmlfile ( .

$xmlfile :

$xmlfile = <<<XML
<Level1>
 <Level2>
  <Level2Item VAR1="1" VAR2="2" ... />
  <Level2Item VAR1="4" VAR2="5" ... />
  <Level2Item VAR1="7" VAR2="8" ... />
 </Level2>
</Level1>
XML;

$xmlfile = '
<Level1>
 <Level2>
  <Level2Item VAR1="1" VAR2="2" ... />
  <Level2Item VAR1="4" VAR2="5" ... />
  <Level2Item VAR1="7" VAR2="8" ... />
 </Level2>
</Level1>';
+1

, SimpleXMLElements , uasort() . ?

0
$xml = simplexml_load_file(...);

$table = array();
foreach ($xml->Level2[0] as $result)
    $table[] = $result->attributes();

function cmp_row($a, $b, $sortColumn)
{
    if ($a == $b)
        return 0;

    return ($a < $b) ? -1 : 1;
}

$sortColumn = 'VAR1'; // make sure it a clean string

uasort($table, create_function('$a,$b', 'return cmp_row($a, $b, "'.$sortColumn.'")'));

You can also save SimpleXMLElements and sort them directly if you want, as apinstein said.

0
source

Source: https://habr.com/ru/post/1706154/


All Articles