In what scenarios is it better to use json_encode () than to use serialize ()?

This is about all I need to ask. I looked through the PHP manual and saw a user message stating that serialization is 45-90% slower than json_encode (he did some tests). But how slowly, slowly? I can find many cons things sprawling around, but not one of them that can be a beginner like me.

I just wrote a script that encoded the array in json and the other to decode it. I did the same with serialization. Obviously, this will not tell me any significant differences between the two.

+3
source share
3 answers

, JSON, PHP, PHP, , JSON.

, , PHP, , JSON, .

, , json- , , .

, JSON- , , , Firebug.

+1

10 000 (), () .

. JSON : - ( - ), , PHP.

+3

/ /, , : - .

, PHP; , sur .

, JSON PHP, , - Javascript PHP.


, :

class A {
    public $a;
    public function __construct($a) {
        $this->a = $a;
    }
}

$test = new A(10);

Now let's serialize and unserialize $ test:

var_dump(unserialize(serialize($test)));

We get:

object(A)[2]
  public 'a' => int 10

those. object, an instance of class A.


Now do the same with JSON:

var_dump(json_decode(json_encode($test)));

Now we only have an instance of stdClass:

object(stdClass)[2]
  public 'a' => int 10

JSON is nice to share data (information about "class A" is important for PHP, but probably does not make much sense for another application); but also has its limitations.

+2
source

Source: https://habr.com/ru/post/1718147/


All Articles