PHP:json_encode与序列化以便存储在MySQL数据库中? [英] PHP: json_encode vs serialize for storing in a MySQL database?

查看:236
本文介绍了PHP:json_encode与序列化以便存储在MySQL数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在表的一个字段中存储一些非结构化"数据(键控数组),并且我目前正在使用serialize()/unserialize()来回转换"从数组到字符串. /p>

但是,每隔一段时间,反序列化数据时都会出错.我相信这些错误是由于我正在序列化的数组中的字符串中的Unicode数据而发生的,尽管有一些使用Unicode数据的记录也可以正常工作. (数据库字段为UTF-8)

我想知道使用json_encode而不是序列化是否会有所作为/使其更具弹性.对于我来说,测试并不是一件容易的事,因为在我的开发环境中,一切都很好,但是在生产环境中,偶尔(大约占记录的1%)会出现错误.

顺便说一句,我知道我正在为找到问题的实际解释而烦恼,只是盲目尝试一些东西,我希望我可以在不花费太多时间的情况下摆脱它.

您认为使用json_encode而不是序列化将使它对序列化错误"更具弹性吗?数据格式对我来说看起来确实更宽容" ...

更新:我得到的实际错误是:

 Notice: unserialize(): Error at offset 401 of 569 bytes in C:\blah.php on line 20

谢谢! 丹尼尔

解决方案

在PHP文档中找到了此内容...

function mb_unserialize($serial_str) { 
    $out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str ); 
    return unserialize($out); 
} 

我不太了解它,但是它可以对以前无法反序列化的数据进行反序列化.现在移至JSON,我将在几周内报告这是否解决了随机获取某些记录损坏"的问题

I'm storing some "unstructured" data (a keyed array) in one field of my table, and i'm currently using serialize() / unserialize() to "convert" back and forth from array to string.

Every now and then, however, I get errors when unserializing the data. I believe these errors happen because of Unicode data in the strings inside the array i'm serializing, although there are some records with Unicode data that work just fine. (DB field is UTF-8)

I'm wondering whether using json_encode instead of serialize will make a difference / make this more resilient. This is not trivial for me to test, since in my dev environment everything works well, but in production, every now and then (about 1% of records) I get an error.

Btw, I know i'm weaseling out of finding an actual explanation for the problem and just blindly trying something, I'm kind of hoping I can get rid of this without spending too much time on it.

Do you think using json_encode instead of serialize will make this more resilient to "serialization errors"? The data format does look more "forgiving" to me...

UPDATE: The actual error i'm getting is:

 Notice: unserialize(): Error at offset 401 of 569 bytes in C:\blah.php on line 20

Thanks! Daniel

解决方案

Found this in the PHP docs...

function mb_unserialize($serial_str) { 
    $out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str ); 
    return unserialize($out); 
} 

I don't quite understand it, but it worked to unserialize the data that I couldn't unserialize before. Moved to JSON now, i'll report in a couple of weeks whether this solved the problem of randomly getting some records "corrupted"

这篇关于PHP:json_encode与序列化以便存储在MySQL数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆