简体   繁体   中英

Convert php array to xml

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

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>';

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM