skip to Main Content

I’m trying to make the following class compatible with native PHP serialization, specifically when running on PHP 8.1.

class SerializableDomDocument extends DOMDocument
{
    private $xmlData;

    public function __sleep(): array
    {
        $this->xmlData = $this->saveXML();
        return ['xmlData'];
    }

    public function __wakeup(): void
    {
        $this->loadXML($this->xmlData);
    }
}

It’s all fine and dandy on lower PHP versions, but 8.1 yields Uncaught Exception: Serialization of 'SerializableDomDocument' is not allowed whenever such an object is attempted to be passed to serialize() function. Here’s a sample of the code that would produce such an exception: https://3v4l.org/m8sgc.

I’m aware of the __serialize() / __unserialize() methods introduced in PHP 7.4, but using them doesn’t seem to be helping either. The following piece of code results into the same exception as can be observed here: https://3v4l.org/ZU0P3.

class SerializableDomDocument extends DOMDocument
{
    public function __serialize(): array
    {
        return ['xmlData' => $this->saveXML()];
    }

    public function __unserialize(array $data): void
    {
        $this->loadXML($data['xmlData']);
    }
}

I’m quite baffled by this problem, and would really appreciate any hints. For the time being it seems like the only way forward would be to introduce an explicit normalizer/denormalizer, which would result in a breaking change in the codebase API. I’d like to avoid that.

2

Answers


  1. It seems this is related to invalid methods or invalid XML content in your DOMDocument. If you do not use it, this works just fine https://3v4l.org/K91Vv

    Login or Signup to reply.
  2. On 10 Aug 2021, this change was commited to version 8.1 RC1:

    Mark DOM classes as not serializable

    So you can no longer serialize those classes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search