1

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)

3
  • 3
    <item><0>apple</0><1>orange</1></item> That's not how it's supposed to be done. Use something like <items><item>apple</item><item>orange</item></items>. Commented Sep 6, 2012 at 12:50
  • 2
    Yes...? Looks like it should work exactly as you want it to. What problem do you have with it? Commented Sep 6, 2012 at 12:51
  • Your right it should be <items><item>apple</item><item>orange</item></items> Commented Sep 6, 2012 at 13:38

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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();

1 Comment

Thanks, I printed the array and your right it is working... It's my xml output thats a dud..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.