Reputation: 19
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
Upvotes: 1
Views: 738
Reputation: 1574
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
Upvotes: 0
Reputation: 59681
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>
Upvotes: 0
Reputation: 1004
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>';
Upvotes: 1