6

I have tried to unserialize a PHP Object.

Warning: unserialize() [function.unserialize]: Node no longer exists in /var/www/app.php on line 42

But why was that happen?

Even if I found a solution to unserialize simplexml objects, its good to know why php cant unserialize objects?

To serialize simplexml object i use this function

function serializeSimpleXML(SimpleXMLElement $xmlObj) 
{

        return serialize($xmlObj->asXML());

}

To unserialize an simplexml objetc i use this function

function unserializeSimpleXML($str) 
{

        return simplexml_load_string(unserialize($str));

}
hakre
  • 193,403
  • 52
  • 435
  • 836
streetparade
  • 32,000
  • 37
  • 101
  • 123
  • Related: [How to serialize/save a DOMElement in $_SESSION?](http://stackoverflow.com/q/10398147/367456) - has an example of how to do it and even add meta information along the nodes. – hakre Jul 01 '12 at 14:44

2 Answers2

13

SimpleXMLElement wraps a libxml resource type. Resources cannot be serialized. On the next invocation, the resource representing the libxml Node object doesn't exist, so unserialization fails. It may be a bug that you are allowed to serialize a SimpleXMLElement at all.

Your solution is the correct one, since text/xml is the correct serialization format for anything XML. However, since it is just a string, there isn't really any reason to serialize the XML string itself.

Note that this has nothing inherently to do with "built-in" PHP classes/objects, but is an implementation detail of SimpleXML (and I think DOM in PHP 5).

Mike
  • 4,976
  • 2
  • 18
  • 11
  • There was a bug in PHP was resolved: https://bugs.php.net/bug.php?id=49800 The nature of the bug was that you were allowed to serialized. – MANCHUCK Jul 16 '12 at 17:57
2

just inherent the class(the main xml class would be best) in a other one

and use __sleep to store the data required to initialize simplexml(any object)

and __wake to reinitialize the object as required

this way you can serialize(any object)

edit: remember this class needs to be accessible first, this can be done by loading(including) the class or an __autoload

borrel
  • 911
  • 9
  • 17
  • You can also use the Serializable interface. – Neil Aitken May 05 '11 at 16:55
  • 1
    nope, i dont see a way to use the serializable interface on a internal php object(as you connot implement 2 classes into your class) – borrel May 13 '11 at 14:04
  • 2
    You can extend the class that you are trying to serialize, and then implement the interface in the child, just as you are with __sleep and __wake. You can implement as many interfaces as you want. – Neil Aitken May 14 '11 at 11:41
  • thanks for the edu, see the note: http://nl.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep – borrel Sep 06 '11 at 11:12