Skip to content

Instantly share code, notes, and snippets.

@mtdowling
Last active September 30, 2021 06:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mtdowling/3877616 to your computer and use it in GitHub Desktop.
Save mtdowling/3877616 to your computer and use it in GitHub Desktop.
Recursive XML to array function
<?php
function xml2array($xml)
{
$arr = array();
foreach ($xml->getNamespaces() + array(null) as $prefix => $namespace) {
foreach ($xml->attributes($namespace) as $key => $value) {
// Add prefixes to prefixed attributes
if (is_string($prefix)) {
$key = $prefix . '.' . $key;
}
$arr['@attributes'][$key] = (string) $value;
}
}
foreach ($xml as $name => $element) {
$value = $element->children() ? xml2array($element) : trim($element);
if ($value) {
if (!isset($arr[$name])) {
$arr[$name] = $value;
} else {
foreach ((array) $value as $k => $v) {
if (is_numeric($k)) {
$arr[$name][] = $v;
} else {
$arr[$name][$k] = array_merge(
(array) $arr[$name][$k],
(array) $v
);
}
}
}
}
}
if ($content = trim((string) $xml)) {
$arr[] = $content;
}
return $arr;
}
@beberlei
Copy link

line 17: just make if if ($element->children()) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment