PHP serialization and JSON

Source: Internet
Author: User
Tags tojson
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


I have something to say

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:

Copy content to clipboard

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:

Copy content to clipboard

Code:


var animal_str = '{"type":"human","name":"hanguofeng","age":22}';
var animal2=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:

Copy content to clipboard

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:

Copy content to clipboard

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:

Copy content to clipboard

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:

Copy content to clipboard

Code:

Array
(
[type] => human
[name] => hanguofeng
[age] => 20
)

Then we will serialize it. The serial code is as follows:

Copy content to clipboard

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:

Copy content to clipboard

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:

Copy content to clipboard

Code:

<?php
$animal_ser='a:3:{s:4:"type";s:5:"human";s:4:"name";s:10:"hanguofeng";s:3:"age";s:2:"20";}';
$animal = unserialize($animal_ser);
print_r($animal);
?>

In the first row, assume that the value of $ animal_ser is the serialized string obtained above. In the second row, the string is restored to the starting array and assigned to $ animal, finally, the $ animal array is output. The output is the same as the original array at the beginning of this section, that is:

Copy content to clipboard

Code:

Array
(
[type] => human
[name] => hanguofeng
[age] => 20
)

In this way, the array is deserialized.

Extended knowledge-serialization and deserialization of custom objects

Serialization of arrays is a basic operation. However, in actual programming, we may often serialize other types of variables, such as serializing a custom object, here is A self-compiled Class A (saved in classa. inc ):

Copy content to clipboard

Code:

<?php
class A {
var $one = 1;
function show_one() {
   echo $this->one;
}
}
?>

Create a class instance in the following code and serialize the instance:

Copy content to clipboard

Code:

<?php
include("classa.inc");
$a=new A;
echo(serialize($a));
?>

The output content is as follows:

Copy content to clipboard

Code:

O:1:"A":1:{s:3:"one";i:1;}

In general, this serialized string outputs the current state of the modified object, that is, the value of I is 1. Next we will analyze the details one by one.
O: 1: because the current variable is a custom Object, the character "O" indicates the Object.
The following "A" identifies the instance of the class of the variable, which is Class.
The name and value of each attribute of the instance are enclosed in braces.
Then we will deserialize it:

Copy content to clipboard

Code:

<?php
include("classa.inc");
$s = 'O:1:"A":1:{s:3:"one";i:1;}';
$a = unserialize($s);
$a->show_one();
?>

In this case, "1" is output, that is, the show_one () method of Class A is called.
You can note that although the serialized strings of an instance do not contain Class methods, we can still call class methods after deserializing them, this feature is supported in PHP4 and later versions (of course, you need to include the class definition file classa. inc ).
Note: You can refer to the section "Language Reference-> Classes and Objects-> Serializing objects-objects in sessions" in the PHP manual.

Serialize to JSON in JavaScript-use json2.js

There is no built-in method for directly serializing objects in JavaScript. Of course you can write one by yourself, but I strongly recommend that you steal a little lazy and use ready-made components here, the official JSON website www.json.org provides a JSON serialized code base for JavaScript objects-json2.js, which you can obtain from here.
After obtaining the json2.js file, you can open the file, which contains a large amount of comments before the file. If your English is good enough, you can omit this section and refer to the comments in this file. As a programmer, you have read a large number of letters and want to see my Chinese characters and letters, then you can continue.
Simple translation of this comment:
See http://www.JSON.org/js.html
This file creates a global object JSON that contains two methods. The methods are as follows:

Copy content to clipboard

Code:

JSON.stringify(value, whitelist)

Any JavaScript value of value, usually an object or Array
Whitelist is an optional array parameter used to determine how object values are serialized.
This method uses a JavaScript value to generate JSON text. During serialization, there are three possible options based on the optional parameter whitelist:
If an object has a toJSON method, this method is called and the return value of the toJSON method is serialized.
Otherwise, if the optional parameter whitelist is an array, the elements in the array will be used to select members when the object is serialized.
Otherwise, if the whitelist parameter is not used, all the members of the object will be serialized.
If the value does not have a JSON representation, such as undefined or function, it will not be serialized. In the object, such values are ignored, and null is replaced in the array.
JSON. stringify (undefined) returns undefined. The date will be serialized as the referenced ISO date.
Example:

Copy content to clipboard

Code:

var text = JSON.stringify(['e', {pluribus: 'unum'}]);
//text is '["e",{"pluribus":"unum"}]'
JSON.parse(text, filter)

This method parses a JSON text and generates a component or array, which may throw a SyntaxError exception.
The optional filter parameter is a function that can filter and convert results. It accepts each key and value, and its return value is used to replace the source value. If it returns the received value, the result will not be changed. If undefined is returned, the Member is deleted.
Example:

Copy content to clipboard

Code:

// Parse text. If a key contains the string "date", the value is converted to the date.
MyData = JSON. parse (text, function (key, value ){
Return key. indexOf ('date')> = 0? New Date (value): value;
});

The above getting started tutorials have given you a basic understanding of how to use json2.js. I will not go into details about this file here, but there is a small tip. If you want to parse a JSON text, you can use the eval () function, which is a built-in function of JavaScript, for example, parsing in JSON. the JSON text generated in the stringify case can be used:

Copy content to clipboard

Code:

var myE = eval('["e",{"pluribus":"unum"}]');

To obtain the object myE.

Serialized as JSON in JavaScript-use prototype. js

If you like me and like to use open-source JavaScript frameworks in your own projects, you may not need to use the json2.js file. Here we use protype. js as an example, the file can be downloaded in the http://www.prototypejs.org, because this article is not about the JavaScript framework, here I suppose you have prototype. I have learned about using js.
Prototype. js provides the toJSON Method for Object objects. You can use the Object. toJSON () method to serialize objects. For example:

Copy content to clipboard

Code:

Var cat =
{
Name: "hellokitty ",
Height: "6 apples"
}
Alert (Object. toJSON (cat ));
// The displayed dialog box contains {"name": "hellokitty", "height": "6 apples "}

In addition, prototype. js also supports JSON, which is mainly used to parse JSON content in Ajax return requests. This is not relevant to our content for the moment, and we will not introduce it any more.

PHP and JSON

We have learned how PHP serializes objects and how to serialize objects into JSON in JavaScript. You may question why I put them together, because their syntax is actually not exactly the same, however, in PHP, JSON text can be deserialized, you can also serialize PHP objects into JSON rather than PHP-style text. This mainly relies on the json_decode and json_encode functions. Note that these two functions are only supported in PHP 5> = 5.2.0, if you want to write a program running in the PHP4 environment, these two functions cannot be used.

Json_decode Function

Syntax
Mixed json_decode (string $ json [, bool $ assoc])
Get a JSON encoded text and convert it to a PHP variable
Parameters
Json
JSON-encoded text
Assoc
If it is TRUE, the returned value is a Union array.
Return Value
Returns an object, or if the optional assoc parameter is TRUE, a union array is returned.

Json_encode Function

Syntax
String json_encode (mixed $ value)
This function returns a JSON expression of the value.
Parameters
Value
The value to be encoded. It can be any type parameter except resource.
This function only works in UTF-8 encoding formats
Return Value
The encoded JSON text is returned when the request succeeds.

Json_decode function instance

The following two examples are based on one of our scenario assumptions: We have a user registration module that works in an "Object-Oriented" way. In the json_decode function instance, on the front-end, we change the user registration information into a class attribute and then pass it to the PHP file in the background (for convenience, Ajax is not needed here ). In the json_encode instance, we reference a js file in the html file. The address points to the PHP file and outputs The json-encoded user object in the PHP file (also for ease of use, we directly generate an object without retrieving information from the database) and output it in html.
Now let's take a look at the front page json_encode.htm. This page imitates the usual registration page and has a form on it. When submitted, the JavaScript function is triggered to generate a user object, set the form content to the attributes of the user object, generate JSON text, and pass it to the json_encode.php file in POST mode. In the js_encode.php file, parse the JSON text into a PHP Object using the json_decode function and output it.
Now let's take a look at the json_encode.html file. The file code is as follows:

Copy content to clipboard

Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>json_decode</title>
<script src="json2.js" type="text/javascript"></script>
<script type="text/javascript">
function JSON_test(o)
{
var user = {
       name:document.getElementById('txt_name').value,
       email:document.getElementById('txt_email').value,
       password:document.getElementById('txt_name').value
}
var json_string = JSON.stringify(user);

Document. getElementById ('txt _ json'). value = json_string;
Alert ("Click OK to submit the form ");
O. submit ();
}
</Script>
</Head>
<Body>
<Form id = "form1" name = "form1" method = "post" action = "json_encode.php" onsubmit = "JSON_test (this)">
<Label for = "txt_name"> name </label>
<P>
<Input type = "text" name = "txt_name" id = "txt_name"/>
</P>
<Label for = "txt_email"> email address </label>
<P>
<Input type = "text" name = "txt_email" id = "txt_email"/>
</P>
<P>
<Label for = "txt_password"> password </label>
</P>
<P>
<Input type = "text" name = "txt_password" id = "txt_password"/>
</P>
<P>
<Input type = "text" name = "txt_json" id = "txt_json"/>
<Label for = "button"> </label>
<Input type = "submit" name = "button" id = "button" value = "JSON"/>
</P>
</Form>
</Body>
</Html>

When a form is submitted, the JavaScript function JSON_text () is triggered. This function first creates a JavaScript Object user and sets its name, email, and password attributes to the values of the corresponding form, respectively, then use the json of the json2.js file. the stringify method converts it to the JSON text json_string, and finally sets the hidden field (here, to make it clear, I show this hidden field as a text box). The value of txt_json is json_string, and submit the form.
The json_encode.php file is as follows:

Copy content to clipboard

Code:

<?php
$json_string = $_POST["txt_json"];
if(ini_get("magic_quotes_gpc")=="1")
{
$json_string=stripslashes($json_string);
}
$user = json_decode($json_string);
echo var_dump($user);
?>

In this file, we first get the value of txt_json in the form field of POST in the json_encode.html file, put it into the variable $ json_string, and then judge. If the current PHP is set to magic_quotes_gpc = On, the incoming double quotation marks will be escaped, in this way, the json_decode function cannot be parsed. Therefore, we need to reverse it. Then, use the json_decode function to convert the JSON text into an object, save it in the $ user variable, and use echo var_dump ($ user); to output the dump of the object. The final result is:

Copy content to clipboard

Code:

object(stdClass)#1 (3) {
   ["name"]=>
   string(10) "hanguofeng"
   ["email"]=>
   string(18) "example@domain.com"
   ["password"]=>
   string(10) "hanguofeng"
}

Json_encode function instance

In this example, json_enode.html and json_encode.php are created by two operators. In the json_decode.html file, the basic form is similar to that in the json_decode.html file, but the difference is that this time we will get the JSON text of the corresponding user from the json_encode.php file. Let's look at this PHP file first:

Copy content to clipboard

Code:

<?php
Class user
{
public $name="";
public $email="";
public $password="";
};
$myUser = new user;
$myUser->name="hanguofeng";
$myUser->email="example@domain.com";
$myUser->password="hanguofeng";
$json_string = json_encode($myUser);
?>
var user = <?php echo($json_string)?>;

This file first creates a class user, then obtains an instance myUser of the user class, and sets the user name, email address, and password. Then, it is converted to JSON text using the json_encode function, save the variable $ json_string and output a piece of JavaScript code to create the global variable user in JavaScript.
To add the json_encode.php file to the json_encode.html file, and obtain the attributes of the user object, as follows:

Copy content to clipboard

Code:

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> json_encode </title>
<Script src = "json_encode.php" type = "text/javascript"> </script>
</Head>
<Body>
<Form id = "form1" name = "form1" method = "post">
<Label for = "txt_name"> name </label>
<P>
<Input type = "text" name = "txt_name" id = "txt_name"/>
</P>
<Label for = "txt_email"> email address </label>
<P>
<Input type = "text" name = "txt_email" id = "txt_email"/>
</P>
<P>
<Label for = "txt_password"> password </label>
</P>
<P>
<Input type = "text" name = "txt_password" id = "txt_password"/>
</P>
</Form>
<Script type = "text/javascript">
Document. getElementById ('txt _ name'). value = user. name;
Document. getElementById ('txt _ email '). value = user. email;
Document. getElementById ('txt _ password'). value = user. password;
</Script>
</Body>
</Html>

In this file, you need to pay attention to two points. First, we use this code to introduce the json_encode.php file as the JavaScript file:

Copy content to clipboard

Code:

<script src="json_encode.php" type="text/javascript"></script>

The second point is:
We add JavaScript code after the text box code to operate the value Attribute of the text box and set the value to the corresponding value of the user object respectively.

Practice
Background
Front-end JavaScript Section
PHP in the background

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.