Skip to content

Instantly share code, notes, and snippets.

@cmbirk
Forked from krusynth/simpleXML_to_object.php
Last active August 29, 2015 14:10
Show Gist options
  • Save cmbirk/0e9a822e878a4f019dcf to your computer and use it in GitHub Desktop.
Save cmbirk/0e9a822e878a4f019dcf to your computer and use it in GitHub Desktop.
<?php
/*
* Translate a non-standard object into an associative array object.
* Super-useful for dealing with simplexml objects.
*/
function simpleXML_to_object($obj)
{
$data = new StdClass();
if(
(is_object($obj) && get_class($obj) == 'SimpleXMLElement')
)
{
/*
* Loop through the children
*/
if (count($obj->children()))
{
foreach ($obj as $key => $value)
{
/*
* If this is actually an array, treat it as such.
* This sort of thing is what makes simpleXML a pain to use.
*/
if (count($obj->$key) > 1)
{
if(!isset($data->$key) || !is_array($data->$key))
{
$data->$key = array();
}
array_push($data->$key, simpleXML_to_object($value));
}
else
{
$data->$key = simpleXML_to_object($value);
}
}
}
if (count($obj->attributes()))
{
foreach ($obj->attributes() as $key => $value)
{
$data->$key = (string) $value;
}
}
/*
* If we have no attributes and no children, treat this as a string.
*/
if (count(get_object_vars($data)) == 0)
{
$data = (string) $obj;
}
elseif (strlen( (string) $obj ))
{
$data->value = (string) $obj;
}
}
elseif (is_array($obj))
{
foreach($obj as $key => $value)
{
$data->$key = simpleXML_to_object($value);
}
}
else {
$data = (string) $obj;
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment