Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to Serialize/Unserialize a SimpleXML Object?

I've seen a few creative solutions for dealing with serialized SPL objects but am looking for more options (or elaborations). I store nested serialized objects - of which, one is SimpleXML - in the database, only to be un-serialized later. This obviously cause some problems.

$s = new SimpleXmlElement('<foo>bar</foo>');
$ss = serialize($s);
$su = unserialize($ss);
// Warning: unserialize() [function.unserialize]: Node no longer exists...

Does anyone have any insight into highly-reliable methods for dealing with serialized SPL objects? __sleep()/__wakeup() overrides? Cast-to-stdClass? Cast-to-string, then serialize?

Any help is appreciated.

[Edit: The scope and variation of these XML schemas are too varied to map with an ORM. They are, at their most fundamental level, arbitrary payloads in stateful processes, triggered within restful APIs.]

like image 599
allnightgrocery Avatar asked Jun 04 '10 01:06

allnightgrocery


1 Answers

Questions on appropriateness notwithstanding, you can turn it back into XML like this:

$xml = $simpleXmlElem->asXML();

And then, when you pull it from the database:

$simpleXmlElem = simplexml_load_string($xml);

As for whether it's appropriate to just serialize large chunks of XML, it can be true that putting XML into the database removes much of the advantage of using a relational system, but you do have the advantage of being able to accommodate an arbitrary workload. If some fields are universal, and/or you gain benefit from normalizing them properly (e.g. you want to select based on those fields), move those into normalized columns.

like image 77
Joe Mastey Avatar answered Oct 17 '22 07:10

Joe Mastey