PHP serialization and JSON

Source: Internet
Author: User

Connection: http://hi.baidu.com/lostdays/blog/item/8d76c300ec4e3c15738b65fa.html

Total directory

What, Why, and How

What
Why
How

PHP serialization syntax
PHP serialization instance
Serialize to JSON in JavaScript-use json2.js
Serialized as JSON in JavaScript-use prototype. js

PHP and JSON

Json_decode Function
Json_encode Function
Json_decode function instance
Json_encode function instance

Practice

Background
Front-end JavaScript Section
PHP in the background


What, Why, and How

What

OK, dear friends, let's start the journey of this new concept. This topic of serialization may not have been paid much attention before. In fact, things actually originated from the PHP manual that day, I found this serialized function, and then I was bored and made another WordPress plug-in. At this time, I used serialization and found that it was indeed very convenient in some occasions.

First, let's explain serialization: in simple words, serialization converts a variable into a word throttling process. The serialization method effectively solves the storage and transmission of objects. For example, I set up an object in JavaScript, I want to save this object to the database on the server. How can I perform this operation? In this case, the serialization of objects is often used. JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for reading and writing, and easy for machine parsing and generation. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language.

JSON and XML are usually compared, both of which are a means of flattening objects (We will explain this "flattening" Later). XML is characterized by a rigorous structure, JSON is easy to read and analyze, because it can easily convert an object into a pipeline stream, for example, the following code:

Code:

{"Type": "human", "name": "hanguofeng", "age": 22}

It is a JSON expression that saves an object. How can we restore it to an object? It is very simple, as follows:

Code:

Var animal_str = {"type": "human", "name": "hanguofeng", "age": 22 };
Var animal = eval (+ animal_str + ));

We use the JavaScript evaluate function to calculate the JSON expression and return the value to obtain an object. Here, I think you will certainly be the same as me, I admire the creators of JSON format. I used to talk about serialization. I was "not careful" about JSON, and I spoke about it so much. Why? No. PHP serialization and JSON are very similar. a php serialization expression is as follows:

Code:
A: 3: {s: 4: "type"; s: 5: "human"; s: 4: "name"; s: 10: "hanguofeng"; s: 3: "age"; s: 2: "20 ";}
It seems that the structure is similar to JSON. In fact, this expression is serialized as follows:
Code:
$ Animal =
Array
(
"Type" => "human ",
"Name" => "hanguofeng ",
"Age" => "20"
);
Okay. The above introduction just gives you a general idea of what serialization and JSON are. You don't have to worry too much about the code here. We will explain it in detail later, let's talk about why serialization is used.

Why

Serialization first emerged as the convenience of data transmission. As I mentioned at the beginning of this article, I have created an object in JavaScript, what should I do if I want to save this object to the database on the server? This is actually a question about how I submit an object to the server from the browser, in this transmission process, we know that we can only pass the pipeline stream. The pipeline stream is one-dimensional (flat), but many objects are multidimensional. If the object to be transmitted is a string, we can simply use it as the passed content. If the object to be passed is an array or another structure, we need to describe it using the transform stream, for example, on the phone, if I ask what your name is, you will tell me that your name is James and James, and I ask you, what is your appearance, you need to describe to me in text. The media for data transmission is often the same as that for this telephone line. We can only pass the gossip stream, but we describe the object process, it is actually a process of serialization.

In addition, serialization can also be used for persistent storage of objects. Maybe you used to store an object in a field of the database like me, now we can do this very simply, and you do not need to set this database field to a special format or varchar (of course, if the object is large, you may need to set it to text ).

How

PHP serialization syntax

Well, I think you have learned about What and Why. At the end of this section, we will talk about more theoretical content, that is, how to use PHP to serialize and deserialize data, how to serialize JavaScript objects (that is, convert them to JSON format), how to deserialize them, and finally how to establish the relationship between JSON and PHP serializing.

PHP provides two functions for serialization and deserialization. These two functions are serialize () and unserialize (), which are applicable to PHP4 and PHP5, the following are the explanations:

Serialize ()

(PHP 4, PHP 5, PECL axis2: 0.1.0-0.1.1)
Serialize-get a stored expression value

Description

String serialize (mixed $ value)
Obtain a stored expression value
This function is used to store or transmit PHP variable values and structures without any loss.
To convert serialized values back to PHP variables, you can use the unserialize () function.

Parameters

Value
The serialized expression. Serialize () processes all types except resource pointers. You can even serialize arrays containing elements pointing to itself. Your serialized arrays or objects that contain loops are stored, and other objects that point to them are lost.
When serializing an object, PHP tries to call its member function _ sleep () first (). This allows objects to perform final cleaning before being serialized. Similarly, when the unserialize () function is used to restore an object, the member function _ wakeup () is called ().

Return Value

Returns a string containing the object's byte stream expression that can be stored anywhere.

Unserialize ()

(PHP 4, PHP 5, PECL axis2: 0.1.0-0.1.1)
Unserialize-get a PHP variable value from a stored expression

Description

Mixed unserialize (string $ str)
Unserialize () gets a simple type of serialized variable and converts it back to the PHP variable value.

Parameters

Str

Serialized string
If the variable to be deserialized is an object, PHP automatically tries to execute the _ wakeup () member functions (if they exist ).
Unserialize_callback_func command: You can set the callback function to be executed during this process, if an undefined class should be instantiated during deserialization (to avoid obtaining an incomplete object "_ PHP_Incomplete_Class "). You can use php. ini, ini_set (), or. htaccess to define "unserialize_callback_func ". When an unspecified class is instantiated, it is called. To block this feature, you only need to set it to null.

Return Value

Returns the converted value, which may be a Boolean variable, a real number, a floating point number, a string, an array, or an object.
If the input string cannot be deserialized, FALSE is returned and a NOTICE error is thrown.
(Translated from the PHP manual)

PHP serialization instance

Serializing and deserializing Arrays

OK. Let's take a look at the example. First, create the sample1.php file. In this file, use the following statement to create a hash array:

Code:
<? Php
$ Animal =
Array
(
"Type" => "human ",
"Name" => "hanguofeng ",
"Age" => "20"
);
?>
To test the value of this array, you can use the print_r () function to output the array. The output result is as follows:

Code:
Array
(
[Type] => human
[Name] => hanguofeng
[Age] => 20
)
Then we will serialize it. The serial code is as follows:

Code:
<? Php
$ Animal =
Array
(
"Type" => "human ",
"Name" => "hanguofeng ",
"Age" => "20"
);
$ Animal_ser = serialize ($ animal );
Echo ($ animal_ser );
?>
Here we serialize the array $ animal, save the returned serialized string in the variable $ animal_ser, and output the following output:

Code:
A: 3: {s: 4: "type"; s: 5: "human"; s: 4: "name"; s: 10: "hanguofeng"; s: 3: "age"; s: 2: "20 ";}
Let's simply parse this string:
A: 3 indicates that this is an array object (a). It has three built-in objects (3)
The content in braces is a list of comma-separated object expressions. Taking s: 4: "type" as an example, it represents a string (s) with a length of 4 bits (4 ), the value is "type", that is, the key of the first element of the hash array.
We will not repeat the subsequent sections. You can try serializing various objects and see how the serialized strings are constructed.
Next, let's take a look at the array's deserialization, which restores the serialized string we generated above to an array. The Code is as follows:

Code:
<? Php
$ Animal_ser = a: 3: {s: 4: "type"; s: 5: "human"; s: 4: "name"; s: 10: "hanguofeng "; s: 3: "age"; s: 2: "20" ;}; <

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.