在PHP中序列化或json? [英] Serialize or json in PHP?

查看:92
本文介绍了在PHP中序列化或json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要用PHP编码数组并将其以纯文本格式存储在MySQL数据库中,我的问题是我应该使用serialize()还是json_encode()?它们各自的优缺点是什么?

So I need to encode an array in PHP and store it in plain text in MySQL database, my question is should I use serialize() or json_encode()? What are the advantages and disadvantages of each of them?

我认为他们中的任何一个都会在这种情况下这样做.但是,您希望选择哪一个?为什么?如果用于数组以外的其他内容?

I think either of them would do in this situation. But which one would you prefer and why? If it is for something other than an array?

推荐答案

serialize的主要优点:它特定于PHP,这意味着它可以表示PHP类型,包括您自己的类的实例-反序列化数据时,您将获得对象,仍然是类的实例.

Main advantage of serialize : it's specific to PHP, which means it can represent PHP types, including instances of your own classes -- and you'll get your objects back, still instances of your classes, when unserializing your data.


json_encode的主要优点:JSON并不是PHP特有的:有一些库可以用几种语言进行读取/写入-这意味着,如果您希望可以可以用另一种语言进行操作的东西比将其更好PHP.


Main advantage of json_encode : JSON is not specific to PHP : there are libraries to read/write it in several languages -- which means it's better if you want something that can be manipulated with another language than PHP.

与序列化的字符串相比,JSON字符串也更容易手动读取/编写/修改 .

A JSON string is also easier to read/write/modify by hand than a serialized one.

另一方面,由于JSON并非特定于PHP,因此它不了解特定于PHP的内容-例如数据类型.

On the other hand, as JSON is not specific to PHP, it's not aware of the stuff that's specific to PHP -- like data-types.


作为几个旁注:


As a couple of sidenotes :

  • 即使两者之间的速度差异很小,也没关系:您可能不会序列化/反序列化大量数据
  • 您确定这是在数据库中存储数据的最佳方法吗?
    • 在数据库中,您将无法对序列化的表链进行很多查询:您将无法在where子句中使用数据,也无法在没有PHP干预的情况下对其进行更新...
    • Even if there is a small difference in speed between those two, it shouldn't matter much : you will probably not serialize/unserialize a lot of data
    • Are you sure this is the best way to store data in a database ?
      • You won't be able to do much queries on serialized strins, in a DB : you will not be able to use your data in where clauses, nor update it without the intervention of PHP...

      这篇关于在PHP中序列化或json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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