PHP JSON or Array to Xml

PHP JSON or Array to XML

Check it here: How to convert array to SimpleXML

and this documentation should help you too

Regarding Json to Array, you can use json_decode to do the same!

How do I Convert jSON to XML

Instead of feeding your function an object, try to feed an array instead:

$jSON = json_decode($raw_data, true);
// ^ add second parameter flag `true`

Example:

function array2xml($array, $xml = false){

if($xml === false){
$xml = new SimpleXMLElement('<result/>');
}

foreach($array as $key => $value){
if(is_array($value)){
array2xml($value, $xml->addChild($key));
} else {
$xml->addChild($key, $value);
}
}

return $xml->asXML();
}

$raw_data = file_get_contents('http://pastebin.com/raw.php?i=pN3QwSHU');
$jSON = json_decode($raw_data, true);

$xml = array2xml($jSON, false);

echo '<pre>';
print_r($xml);

Sample Output

how to convert json response data to xml

function array2xml($array, $xml = false){

if($xml === false){
$xml = new SimpleXMLElement('<result/>');
}

foreach($array as $key => $value){
if(is_array($value)){
array2xml($value, $xml->addChild($key));
} else {
$xml->addChild($key, $value);
}
}

return $xml->asXML();
}

$jSON = json_decode($raw_data, true);

$xml = array2xml($jSON, false);

echo '<pre>';
print_r($xml);

Is there an xml_encode() like json_encode() in PHP?

JSON can express php arrays, integers, strings, etc. natively. XML has no such concepts - just elements, attributes, and text. If you want to transfer an object verbatim, use JSON. If you want to implement a complex API, use XML, for example the php DOM interface.

Convert JSON to XML using PHP

It has been explained here:
Is there some way to convert json to xml in PHP?

Use json_decode() and PEAR::XML_Serializer

Convert an array to XML or JSON

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

XML to JSON or array? PHP

http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/



Related Topics



Leave a reply



Submit