Created
February 25, 2020 15:00
-
-
Save juukie/45efdd78fd07adbd58a4184e8bfc0ca8 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* @param $object | |
* @return array|string | |
*/ | |
function simplexml_to_array($object) { | |
if (! is_object($object)) { | |
return $object; | |
} | |
$attributes = $object->attributes(); | |
if ($object->count() === 0 && count($attributes) === 0) { | |
return (string) $object; | |
} | |
$return = []; | |
if (count($attributes) > 0) { | |
if ($object->count() === 0) { | |
$return['value'] = (string) $object; | |
} | |
foreach ($attributes as $k => $v) { | |
$return[$k] = (string) $v; | |
} | |
} | |
$children = $object->children(); | |
$childcount = []; | |
$count = count($children); | |
for ($i = 0; $i < $count; $i++) { | |
$v = $children[$i]; | |
$k = $children[$i]->getName(); | |
if (array_key_exists($k,$return)) { | |
$childcount[$k]++; | |
if ($childcount[$k] === 1) { | |
$tmp = $return[$k]; | |
$return[$k] = []; | |
$return[$k][] = simplexml_to_array($tmp); | |
} | |
$return[$k][] = simplexml_to_array($v); | |
} else { | |
$return[$k] = simplexml_to_array($v); | |
$childcount[$k] = 0; | |
} | |
} | |
return $return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment