Serialize and Unserialize SimpleXML in php

Serialize is useful for storing or passing PHP values around without losing type and structure.
But if you want to serialize a SimpleXml object, you will have some problem on unserialize with the error Warning: unserialize() [function.unserialize]: Node no longer exists in DIRECTORY/FILE.php on line X”.
So I found some solutions on the web and in the php documentation like this one : http://theserverpages.com/php/manual/en/ref.simplexml.php#52761

Replacing SimpleXMLObject with stdClass is a good idea but in this solution we loose all of attributes, and how can we make simplexml->xpath after ?

So I’ find one solution that give me a SimpleXMLObject on unserializeI have a specific serialize function which detect the type of element to serialize. There is a specific treatement for SimpleXMLObject.

Just check the code :

$xmlfile = simplexml_load_file("projets.xml");
$xmlser = serializemmp($xmlfile);
$xmlunser = unserializemmp($xmlser);
print_r($xmlunser);

The specific serialize function. If we have a SimpleXMLObject, I make a asXML() which give a string representation more easy to store
function serializemmp($toserialize){
if(is_a($toserialize, “SimpleXMLElement”)){
$stdClass = new stdClass();
$stdClass->type = get_class($toserialize);
$stdClass->data = $toserialize->asXml();
}
return serialize($stdClass);

}
In the specific serialized object we store the type of object that we have before the transformation. So if we have a SimpleXMLObject we just make a simplexml_load_string on obj->data.

function unserializemmp($tounserialize){
$tounserialize = unserialize($tounserialize);
if(is_a($tounserialize, “stdClass”)){
if($tounserialize->type == “SimpleXMLElement”){
$tounserialize = simplexml_load_string($tounserialize->data);
}
}
return $tounserialize;
}

I don’t know if this is really a good solution to serialize xml objects, but this is way where we can always access to the functionnality of SimpleXML


About this entry