Skip to content

Instantly share code, notes, and snippets.

@jasondmoss
Last active July 15, 2025 10:09
Show Gist options
  • Select an option

  • Save jasondmoss/7344311 to your computer and use it in GitHub Desktop.

Select an option

Save jasondmoss/7344311 to your computer and use it in GitHub Desktop.
Convert a SimpleXML object to associative array
<?php
/**
* Convert a SimpleXML object to an associative array
*
* @param object $xmlObject
*
* @return array
* @access public
*/
function simpleXmlToArray($xmlObject)
{
$array = [];
foreach ($xmlObject->children() as $node) {
$array[$node->getName()] = is_array($node) ? simplexml_to_array($node) : (string) $node;
}
return $array;
}
@adampatterson
Copy link

Will this give the expected result?

json_decode(json_encode($xml), true);

For the most part this worked for me, but I found some instances maybe 5 levels in that had CDATA content and were simply converted to an empty array.

@jasondmoss
Copy link
Author

Thanks everyone for chipping in to this simple little snippet (which worked for my purpose at the time). I mainly just use Gists as 'notes to self'. This has just kept growing :) Great job.

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