PHP序列化/反序列化错误

9
我们在使用PHP序列化/反序列化过程中遇到了一个奇怪的问题。我们已经将特定字符串序列化并存储在MySQL中(UTF-8字符集)。当尝试反序列化时,出现了错误。
例如: 字符串:
"Anoop did a great job cutting out pictures from the magazine that started with the letter P."
数据库中序列化数据:
s:96:"Anoop did a great job cutting out pictures from the magazine that started with the letter P.";
而在反序列化时,我们遇到了这个错误“Notice - unserialize (): Error at offset 2 of 101 bytes”。我们注意到字符串长度不同。这个问题的原因是什么?
非常感谢您的帮助!谢谢!

1
请看一下,希望您能找到解决方案... - Akshay Paghdar
2
我最近停止了数据序列化,开始只存储JSON对象,因为序列化问题让我感到非常烦恼。 - Dave
3个回答

3

您的连接中可能没有使用utf-8编码,或者您的PHP上下文不是utf-8编码。

尝试使用以下SQL语句:

SET CLIENT_ENCODING = utf8 

在获取您的数据之前,请进行尝试/验证:
ini_set ('default_charset' , 'UTF-8' );
setlocale (LC_ALL, 'de_DE.UTF-8'); # or what your favorit

1
你看到第二个字符串中有一个分号了吗?UTF-8并不总是使用一个字节,它的长度可以是1到4个字节。
从数据库解码字符串时,请确保输入到数据库时使用了正确的字符集进行编码。
我使用一个表单在数据库中创建记录,其中包含一个有效的JSON内容字段,但其中包含花式撇号。如果表单所在页面没有

标签,则会发生问题。

在头部设置错误的编码后,将数据发送到数据库中。然后,当json_decode尝试将字符串转换为对象时,每次都会失败。

1

PHP的序列化/反序列化没有问题,

就像这样做:

$string = "Anoop did a great job cutting out pictures from the magazine that started with the letter P. ";
echo $string = serialize($string);
echo '<br>';
echo unserialize($string);

那么就没有错误。

如果您直接对字符串进行unserialize,则会显示与之前相同的错误。

$string = "Anoop did a great job cutting out pictures from the magazine that started with the letter P. ";
//echo $string = serialize($string);
echo '<br>';
echo unserialize($string);

这对我有效,你可以试一下。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接