Created
December 20, 2015 13:37
-
-
Save osde8info/b1b29bf95752d3408ed2 to your computer and use it in GitHub Desktop.
php assoc array to xml and json serialiser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// SETUP PHP ARRAY USING HARDCODED JSON INSTEAD OF HARDCODED PHP | |
include 'q.php'; | |
// ACTUAL ASSOC ARRAY TO XML & JSON SERIALISATION STARTS HERE | |
function aatoxml($xml,$ele) { | |
if (is_array($ele)) { | |
foreach ($ele as $k=>$v) { | |
if ($k != '@attributes') { | |
if (is_array($v)) { | |
$mononode = true; | |
foreach ($v as $ckey=>$cval) { | |
if (is_numeric($ckey)) { | |
aatoxml($xml->addChild($k),$cval); | |
$mononode = false; | |
} | |
} | |
if ($mononode) { | |
aatoxml($xml->addChild($k),$v); | |
} | |
} | |
else { | |
$xml->addChild($k,$v); | |
} | |
} | |
else { | |
foreach ($v as $aname=>$avalue) { | |
$xml->addAttribute($aname,$avalue); | |
} | |
} | |
} | |
} | |
} | |
// $aa IS AN ASSOC ARRAY THAT CONTAINS DATA WE WANT TO TURN INTO XML STRING | |
$xml = new SimpleXMLElement('<account></account>'); | |
aatoxml($xml,$aa); | |
echo $xml->asXML(); | |
echo PHP_EOL; | |
echo json_encode($xml,JSON_PRETTY_PRINT); | |
echo PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment