user1639745
user1639745

Reputation: 35

Add existing array to 3d array

I'm trying to build a 3d php array, that ultimately gets outputted as xml... This is the code I'm trying to use to prove the concept...

$test = array('apple','orange');
$results = Array(
  'success' => '1',
  'error_number' => '',
  'error_message' => '',
  'results' => Array (
       'number_of_reports' => mysql_num_rows($run),
       'item' => $test
   )
);

I want the resulting array to look like

<success>1</success>
<error_number/>
<error_message/>
<results>
     <number_of_reports>18</number_of_reports>
     <item>
         <0>apple</0>
         <1>orange</1>
     </item>
</results>

In reality the apple and orange array would be a 3d one in itself... If you've ever used the ebay api... you'll have an idea of what I'm trying to do (I think)

Upvotes: 1

Views: 86

Answers (2)

Eduar Carvajal
Eduar Carvajal

Reputation: 41

Try it:

Code:

<?php
$test = array('apple','orange');
$results = Array(
  'success' => '1',
  'error_number' => '',
  'error_message' => '',
  'results' => Array (
       'number_of_reports' => 1,
       'item' => $test
   )
);

print_r($results);
function addChild1($xml, $item, $clave)
{
    if(is_array($item)){
        $tempNode = $xml->addChild($clave,'');
        foreach ($item as $a => $b)
        {
            addChild1($tempNode, $b, $a);
        }           
    } else {
        $xml->addChild("$clave", "$item");
    }
}

$xml = new SimpleXMLElement('<root/>');
addChild1($xml, $results,'data');
$ret = $xml->asXML();

print $ret;

Output:

<?xml version="1.0"?>
<root><data><success>1</success><error_number></error_number><error_message></error_message><results><number_of_reports>1</number_of_reports><item><0>apple</0><1>orange</1></item></results></data></root>

Upvotes: 2

Abid Hussain
Abid Hussain

Reputation: 7762

See below URL. I think it very use full to you:-

How to convert array to SimpleXML

Or Try it:-

$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

Upvotes: 0

Related Questions