Convert an array to XML or JSON
39,525
Solution 1
This works for associative arrays.
function array2xml($array, $node_name="root") {
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$root = $dom->createElement($node_name);
$dom->appendChild($root);
$array2xml = function ($node, $array) use ($dom, &$array2xml) {
foreach($array as $key => $value){
if ( is_array($value) ) {
$n = $dom->createElement($key);
$node->appendChild($n);
$array2xml($n, $value);
}else{
$attr = $dom->createAttribute($key);
$attr->value = $value;
$node->appendChild($attr);
}
}
};
$array2xml($root, $array);
return $dom->saveXML();
}
Solution 2
JSON, use the json_encode function:
<?php echo json_encode( $array); ?>
XML, see this question.
Solution 3
Which programming language are you using ?
In case you are using PHP you can use the following to convert to JSON:
$json = json_encode($your_array);
And for XML you can check the following answer: How to convert array to SimpleXML.
Hope it helps.
Comments
-
known reg over 3 years
I want to convert the array below
Array ( [city] => Array ( [0] => Array ( [0] => Rd [1] => E ) [1] => B [2] => P [3] => R [4] => S [5] => G [6] => C ) [dis] => 1.4 )
into XML format or JSON. Someone may help please?