Saturday, August 28, 2010

How to make php DOMDocument Serializable

The default DOMDocument class in php is not serializable.
That is, if you run $myDOM = serialize($oDOM), then unserialize($myDOM)
you will get back the object of type DOMDocument, but the data
will be lost, so you will basically get back the empty DOM Document,
not even the root element will be there, nada!

But it's easy to fix that. All you have to do is
extend the DOMDocument and implement Serializable interface

This is how you do it:

class MyDOMDocument extends DOMDocument implements Serializable
{

public function __construct(){

parent::__construct();

}

public function serialize(){
$s = $this->saveXML();
return $s;
}

public function unserialize($serialized)
{
$this->loadXML($serialized);

}
}

Ok, now if you serialize() and then unserialize() you will get back
the object of type MyDOMDocument and it will have the same data
as it had before serialization.

Of cause this will only work with PHP 5.2 or better and SPL libraries enabled (they are by default in php5)

1 comment:

  1. THANK YOU! This has been bugging me for, um, a couple of hours now.

    ReplyDelete