DOMDocument serialization in PHP 8.1
P粉891237912
P粉891237912 2024-01-16 11:19:03
0
1
555

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);
    }
}

Everything was fine on lower PHP versions, but 8.1 throws Uncaught exception: Serialization of 'SerializedDomDocument' is not allowed whenever trying to pass such an object to serialize() function. Here is an example of code that would generate 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 help either. The following code snippet causes the same exception 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 very confused about this problem and would really appreciate any tips. At the moment it seems the only way forward is to introduce explicit normalizers/denormalizers, which will result in significant changes to the codebase API. I want to avoid this situation.

P粉891237912
P粉891237912

reply all(1)
P粉041881924

On August 10, 2021, this change was committed to version 8.1 RC1:

Mark DOM classes as non-serializable

So you can no longer serialize these classes.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template