Skip to content

Instantly share code, notes, and snippets.

@juukie
Created February 25, 2020 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juukie/45efdd78fd07adbd58a4184e8bfc0ca8 to your computer and use it in GitHub Desktop.
Save juukie/45efdd78fd07adbd58a4184e8bfc0ca8 to your computer and use it in GitHub Desktop.
<?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