sineverba
sineverba

Reputation: 5172

Simplexml elements extracts only first element but i need all elements

i've this XML structure:

<response status="success">
<campaign>
 <id>1</id>
 <nameCampaign>Raccolta Punti CCN</nameCampaign>
 <type>points</type>
 <balances>
     <balance>10.00 </balance>
  </balances>
 </campaign>
 <campaign>
 <id>6</id>
 <nameCampaign>Abbonamenti</nameCampaign>
 <type>subscription</type>
  <balances>
    <balance>6.00 Lampada solare</balance>
  </balances>
  <balances>
   <balance>4.00 doccia solare</balance>
  </balances>
  <balances>
     <balance>3.00 trifacciale</balance>
  </balances>
 </campaign>
</response>

And I need convert in array.

If i use

 foreach($result->campaign as $bilancio) {
    $balance[] = array  (   'nameCampaign'  =>  (string)$bilancio->nameCampaign,
                            'balances'      =>  (string)$bilancio->balances->balance    );      
} // foreach

I obtain this array

    Array
  (
[0] => Array
    (
        [nameCampaign] => Raccolta Punti CCN
        [balances] => 10.00 
    )

[1] => Array
    (
        [nameCampaign] => Abbonamenti
        [balances] => 6.00 Lampada solare
    )
  )

How could you note, id 6 has three sub-node (balances->balance) and not only one. How i could obtain a complete array?

Thank you to all and have a nice weekend!

Upvotes: 1

Views: 1325

Answers (1)

Dale
Dale

Reputation: 10469

Instead of reading (which will always give you the first element only with simeplxml), you iterate over all elements with foreach.

Here's a way:

$balance = array();
foreach ($result->campaign as $campaign)
{
    $arr = array();
    foreach ($campaign->balances as $campaignBalance)
    {
        $arr[] = (string) $campaignBalance->balance;
    }

    $balance[] = array(
        'nameCampaign' => (string) $campaign->nameCampaign,
        'balances'     => $arr
    );
}

print_r($balance);

Which will give you this result:

Array
(
    [0] => Array
        (
            [nameCampaign] => Raccolta Punti CCN
            [balances] => Array
                (
                    [0] => 10.00
                )
        )
    [1] => Array
        (
            [nameCampaign] => Abbonamenti
            [balances] => Array
                (
                    [0] => 6.00 Lampada solare
                    [1] => 4.00 doccia solare
                    [2] => 3.00 trifacciale
                )
        )
)

Upvotes: 1

Related Questions