php反序列化存储在DB字段中的序列化对象

I am trying to serialize a php object then unserialize it.

When I serialize, and then put the obtained string in a file, then read the file and unserialize, all works fine.

When I serialize, and then store the obtained string in a database field, then read it back and try to unserialize, that does not work. I noticed that the string I read from the database contains some special characters (like &quote;). I tried to get rid of those by using htmlspecialchars_decode, but still the unserialize does not work (the message : unserialize(): Error at offset 1774 of 24239 bytes). When I try to see those characters I do not see anything special.

Any help?

Store it in a BLOB / BINARY column, not in TEXT or (VAR)CHAR. Serialization of certain properties contain NULL-bytes for instance.

As @Barmar says, the documentation states this explicitly:

Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

To illustrate:

<?php
class Foo { private $bar = "baz";} 
$string = serialize(new Foo()); 
echo $string.PHP_EOL;
for($i = 0; $i < strlen($string); $i++){ 
    echo $string[$i]."(".dechex(ord($string[$i])).")";
}

Outputs visually:

O:3:"Foo":1:{s:8:"Foobar";s:3:"baz";}

BUT: there's more then the eye can see:

O(4f):(3a)3(33):(3a)"(22)F(46)o(6f)o(6f)"(22):(3a)1(31):(3a){..
    (7b)s(73):(3a)8(38):(3a)"(22)(0)F(46)o(6f)o(6f)(0)b(62)a(61)r(72)"
                                  ^ ----------------^-- there's two of your NULL bytes.