Last active
August 29, 2015 14:17
-
-
Save kopiro/cd1160f0afa975ea6985 to your computer and use it in GitHub Desktop.
xml2array/xmlencode in PHP
This file contains hidden or 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 | |
function xml_decode($input) { | |
return current(xml2array(simplexml_load_string($input))); | |
} | |
function xml2array($xml) { | |
$arr = array(); | |
foreach ($xml->children() as $r) { | |
$t = array(); | |
if (count($r->children()) == 0) { | |
$arr[$r->getName()] = strval($r); | |
} else { | |
$arr[$r->getName()][] = xml2array($r); | |
} | |
} | |
return $arr; | |
} | |
function xml_encode($array, $root = 'elements', $xml = null) { | |
if ($xml === null) $xml = new SimpleXMLElement('<'.$root.'/>'); | |
$sroot = preg_replace('~s$~', '', $root); | |
foreach ($array as $key => $value) { | |
if (is_array($value) || is_object($value)) { | |
$skey = is_numeric($key) ? $sroot : $key; | |
xml_encode($value, $skey, $xml->addChild($skey)); | |
} else { | |
if (!is_numeric($key)) { | |
$xml->{$key} = $value; | |
} else { | |
$xml->{$sroot} = $value; | |
} | |
} | |
} | |
return $xml->asXML(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment