Created
September 6, 2013 13:33
-
-
Save krusynth/6463853 to your computer and use it in GitHub Desktop.
Translates a simpleXML object into a standard PHP object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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