How to use php serialize() and unserialize() Ask Question

How to use php serialize() and unserialize() Ask Question

My problem is very basic.

I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.

EDIT:

<?php

$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);

?>

output:

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?

ベストアンサー1

A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.


Take for example this common problem:

How do I pass a PHP array to Javascript?

PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

The answer is serializationPHP/Javascript の場合、JSON の方が実際にはより適切なシリアル化形式です。

{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }

Javascript を使用すると、これを簡単に実際の Javascript 配列に変換できます。

ただし、これは同じデータ構造の有効な表現です。

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

しかし、PHP だけがこれを使用しており、他の場所ではこの形式はほとんどサポートされていません。
ただし、これは非常に一般的であり、十分にサポートされています。

<array>
    <element key='1'>elem 1</element>
    <element key='2'>elem 2</element>
    <element key='3'>elem 3</element>
</array>

パスしなければならない状況はたくさんあります複雑なデータ構造任意のデータ構造を文字列として表すシリアル化により、この問題を解決できます。

おすすめ記事