Skip to content

Instantly share code, notes, and snippets.

@tvlooy
Created January 5, 2017 17:03
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 tvlooy/4d0abe8fffbeb5b8e4e029aaea61e72a to your computer and use it in GitHub Desktop.
Save tvlooy/4d0abe8fffbeb5b8e4e029aaea61e72a to your computer and use it in GitHub Desktop.
SimpleXML to array
<?php
function xmlToArray(SimpleXMLElement $xmlObject) : array
{
$array = [];
foreach ((array) $xmlObject as $elementName => $value) {
if (is_object($value)) {
if (empty($value)) {
$array[$elementName] = '';
} else {
$array[$elementName] = xmlToArray($value);
}
} elseif (is_array($value)) {
foreach ($value as $arrayValue) {
$array[$elementName][] = xmlToArray($arrayValue);
}
} else {
$array[$elementName] = $value;
}
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment