1

please review my code, i have tried several suggestion on various threads, i either get a blank out put or a string.

my code

   <?php
       $input_array = array (
         'name' => 'John Doe',
         'course' => 'Computer Science',
         'age' => 'twenty one'
        );
       $xml = new SimpleXMLElement('<root/>');
       array_walk_recursive(array_flip($input_array), array ($xml, 'addChild'));
       print $xml->asXML();
    ?>

output John DoeComputer Sciencetwenty one

1
  • I'd suggest doing this with a for or foreach loop instead of trying to make a one-liner with array_walk_recursive. Commented Jan 6, 2015 at 15:57

3 Answers 3

1

The web browser is parsing the tags which is why they appear to not be there.

Right click and view source. Or surround the output with <pre> tags.

print '<pre>';
print $xml->asXML();
print '</pre>';
Sign up to request clarification or add additional context in comments.

Comments

0

This should work for you:

<?php

    $input_array = array (
                   'name' => 'John Doe',
                   'course' => 'Computer Science',
                   'age' => 'twenty one'
                  );

    $xml = new SimpleXMLElement('<root/>');
    $arr = array_flip($input_array);
    array_walk_recursive($arr, array( $xml, 'addChild'));
                       //^^^ Can't use array_filp directly otherwise: Strict Standards: Only variables should be passed by reference

    print $xml->asXML();

?>

To get a nice formatted output you could do this:

header('Content-type: text/xml');

Output:

<root>
  <name>John Doe</name>
  <course>Computer Science</course>
  <age>twenty one</age>
</root>

1 Comment

Thanks a lot. It was the content type that I didn't specify that caused the error.
0

a short one:

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

results in

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

For converting php array to xml refer this doc in that very good solution available

Comments

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.