SimpleXML is neat.  Some people don't think it is so simple.  Boy, use the old stuff.  The DOM-XML stuff.

Anyhow, one annoying thing about SimpleXML has to do with caching.  When using web services, we often cache the contents we get back.  We were having a problem where we would get an error about a SimpleXML node not existing.  We were caching the data in memcached which serializes the variable.  So, when it unserialized the variable, there were references in there to some SimpleXML nodes that we did not take care of.  Basically, a tag like:

<foo>bar</foo>

is a string.  But a tag like:

<foo></foo>

is an empty SimpleXML Object.  That is a little annoying, but I don't feel like digging into the C code and figuring out why.  So, we just work around it.  We made a recursive function to do the dirty work for us.

function makeArray($obj) {
$arr = (array)$obj;
if(empty($arr)){
$arr = "";
} else {
foreach($arr as $key=>$value){
if(!is_scalar($value)){
$arr[$key] = makeArray($value);
}
}
}
return $arr;
}

That will turn whatever you pass it into an array or empty string if it is empty.

But, while I was hacking around tonight, I came up with another idea.  Check out this hackery:

$data = json_decode(json_encode($data));

Yeah!  One liner.  That converts all the SimpleXML elements into stdClass objects.  All other vars are left intact.

Ok, so this is where someone in the comments can tell me about the magic SimpleXML method or magic OOP function I have missed to take care of all this.  Go ahead, please make my code faster.  I dare you.