简体   繁体   English

PHP序列化/反序列化错误

[英]PHP serialize/unserialize error

We have came across a strange issue while using PHP serialize/unserialize. 我们在使用PHP序列化/反序列化时遇到了一个奇怪的问题。 We have serialized and stored in a particular string in mysql (UTF-8 collation). 我们已经序列化并存储在mysql中的特定字符串中(UTF-8整理)。 When unserializing the same it returns error. 反序列化时会返回错误。

Eg: String: 例如:字符串:

"Anoop did a great job cutting out pictures from the magazine that started with the letter P. " “Anoop很好地剪下了以P字母开头的杂志中的图片。”

Serialized data in DB : DB中的序列化数据:

s:96:"Anoop did a great job cutting out pictures from the magazine that started with the letter P. "; s:96:“Anoop很好地剪掉了以P字母开头的杂志中的照片。”

While unserializing we got this error Notice - unserialize (): Error at offset 2 of 101 bytes . 虽然反序列化我们得到了这个错误Notice - unserialize (): Error at offset 2 of 101 bytes We noticed that the string length is different. 我们注意到字符串长度不同。 What would be the cause for this issue. 这个问题的原因是什么?

Any help would be really appreciated. 任何帮助将非常感激。 Thanks! 谢谢!

it is possible that you don't use utf-8 within your connection or your PHP context is not utf-8? 您可能不在连接中使用utf-8,或者您的PHP上下文不是utf-8?

try to use the SQL: 尝试使用SQL:

SET CLIENT_ENCODING = utf8 

Befor you get your data. 因为你得到你的数据。

try/verify: 尝试/验证:

ini_set ('default_charset' , 'UTF-8' );
setlocale (LC_ALL, 'de_DE.UTF-8'); # or what your favorit

you see that there is a semicolon in the second string? 你看到第二个字符串中有分号? UTF-8 does not use one byte all the time, it's 1 to 4 bytes. UTF-8不会一直使用一个字节,它是1到4个字节。

When decoding strings from the database, make sure the input was encoded with the correct charset when it was input to the database. 从数据库解码字符串时,请确保输入在输入到数据库时使用正确的字符集进行编码。

I was using a form to create records in the DB which had a content field that was valid JSON, but it included curly apostrophes. 我使用表单在数据库中创建记录,其内容字段是有效的JSON,但它包含了撇号。 If the page with the form did not have 如果带有表单的页面没有

in the head, then the data was sent to the database with the wrong encoding. 在头部,然后使用错误的编码将数据发送到数据库。 Then, when json_decode tried to convert the string to an object, it failed every time. 然后,当json_decode尝试将字符串转换为对象时,它每次都失败。

PHP serialize/unserialize has no problem , PHP序列化/反序列化没有问题,

is do it like 是这样的

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

Then there is not error. 然后没有错误。

If you do direct unserialize the string then the same error display as you display previously. 如果直接反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);

It works for me you will try this. 它适用于你,你会试试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM