Original link: http://hi.baidu.com/lostdays/blog/item/8d76c300ec4e3c15738b65fa.html
General Catalog
What, Why, How
What
Why
How
PHP serialization syntax
PHP serialization example
Serialize to JSON in JavaScript — using json2.js
Serialize to JSON in JavaScript—using prototype.js
PHP with the JSON
json_decode function
json_encode function
json_decode function example
json_encode function example
practice gives true
knowledge background explanation
Frontend JavaScript part
Backend PHP part
What, Why, How
What
Ok, dear friends, let us start the journey of this new concept. Maybe everyone has not paid much attention to the topic of serialization before. In fact, it originated from the day I casually flipped through the PHP manual and found this serialization After that, I was bored and made a WordPress plug-in. At this time, I used serialization and found that it is indeed very convenient in certain situations.
Let’s first explain serialization: Simply put, serialization is the process of converting variables into a byte stream. The introduction of serialization effectively solves the problem of object storage and transmission. For example, I created an object in JavaScript and now I want to save this object to the server-side database. So how do I operate it? , this time the serialization of objects is often used. In the serialization of JavaScript, we have to mention JSON. JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for humans to read and write, and easy for machines to parse and generate. It is based on JavaScript Programming Language, a subset of Standard ECMA-262 3rd Edition - December 1999. JSON uses a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language.
People usually compare JSON and XML. Both are a means of flattening objects (we will explain this "flattening" later). XML is characterized by a rigorous structure, while JSON is characterized by being simple and easy to read. It is easy to use the program for analysis, because it can easily convert an object into the form of a character stream, such as the following code:
Code:
{"type":"human","name":"hanguofeng","age": 22}
is a JSON expression that saves an object. How do we restore it to an object? It's very simple, as follows:
Code:
var animal_str = '{"type":"human","name":"hanguofeng","age":22}';
var animal2=eval('(' + animal_str + ')');
We use the JavaScript evaluation function to operate the JSON expression and return the value to obtain an object. At this point, I think you will definitely understand Like me, I admire the thinking of the creator of the JSON format. I was originally going to talk about serialization, but I "accidentally" mentioned JSON and talked about it so much. Haha, did I get off topic? No, PHP serialization is very similar to JSON. 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";}
Its structure looks somewhat similar to JSON. In fact, this expression is the serialized result of the following array:
Code:
$animal =
array
(
"type" => "human",
"name" => "hanguofeng",
"age" => "20"
);
OK, the above introduction is just to give you a rough idea of what serialization and JSON are. You don’t need to get too entangled with the code here. We will explain it in detail later. Let’s talk about why we should use serialization. change.
Why
serialization first appeared as a convenience for data transmission. As I asked the question at the beginning of this article, I created an object in JavaScript. I now want to save this object to the server-side database. How should I do it? In fact, it is a question of "how do I submit an object from the browser to the server". During this transmission process, we know that only the character stream can actually be transmitted. The character stream is one-dimensional (flat), but many objects But it is multi-dimensional. If the object to be transferred is a string, it is very simple. We can directly use it as the transferred content. If the object to be transferred is an array or other structure, we need to use characters. To describe him, for example, on the phone, if I ask you what your name is, you will tell me that your name is Zhang San or Li Si, and if I ask you, what do you look like, you need to use words. It was described to me that the medium through which we transmit data is often the same as this telephone line, which can only transmit character streams, and the process by which we describe objects is actually a process of serialization.
In addition, serialization can also be used for persistent storage of objects. Maybe you, like me, once thought about storing an object in a certain field of the database. Now we can do this very simply, and, Your database field does not need to be set to a special format, just set it to varchar (of course, if the object is large, you may need to set it to text).
How
PHP serialization syntax
Okay, I think you have understood the questions of What and Why. At the end of this section, we will talk about something more theoretical, that is, how to use PHP to serialize and deserialize data, how to Serialize JavaScript objects (that is, change them to JSON format) and how to deserialize them. Finally, how to establish a relationship between JSON and PHP serialization.
PHP provides us with two functions for serialization and deserialization operations. These two functions are: serialize() and unserialize(). They are suitable for PHP4 and PHP5. They are explained below:
serialize()
(PHP 4, PHP 5, PECL axis2:0.1.0-0.1.1)
serialize — Get a storable representation value
string
serialize ( mixed $value )
Get a storable representation value. This function is used to losslessly store or transfer PHP variable values and structures.
If you need to convert the serialized value back to a PHP variable, you can use the unserialize() function.
Parameter
value
That is, the expression being serialized. serialize() handles all types except resource pointers, and you can even serialize an array containing elements pointing to itself. The arrays or objects you serialize that contain loop pointers will still be stored, but other pointers will be lost.
When serializing an object, PHP attempts to first call its member function __sleep(). This will allow for things like final cleanup before the object is serialized. Similarly, when the object is restored using the unserialize() function, the member function __wakeup() will be called.
The return value
returns a string containing a byte stream expression of the object that can be stored anywhere.
unserialize()
(PHP 4, PHP 5, PECL axis2:0.1.0-0.1.1)
Get
a PHP variable value from a stored expression
mixed unserialize ( string $str )
unserialize() takes a simple type of serialized variable and converts it back to a PHP variable value.
Parameter
str
serialized string If the deserialized variable is an object, after successfully restoring the object's structure, PHP will automatically try to execute the object's __wakeup() member function (if it exists).
unserialize_callback_func directive: You can set the callback function to be executed during this process, if an undefined class should be instantiated during deserialization (to avoid getting an incomplete object "__PHP_Incomplete_Class"). You can use php.ini, ini_set() or .htaccess to define "unserialize_callback_func". It is called when an undefined class is instantiated. To disable this feature simply set it to empty.
The return value
returns the converted value, which may be a Boolean variable, real number, floating point number, string, array or object.
If the incoming string cannot be deserialized, FALSE is returned and a NOTICE error is thrown.
(The above is translated from the PHP manual)
Serialization and deserialization of
PHP serialization instance
arrayOK, let us learn it with an example. First, please create the sample1.php file. We use the following statement in this file. Create a hash array:
Code:
<?php
$animal =
array
(
"type" => "human",
"name" => "hanguofeng",
"age" => "20"
);
?>
In order to test the value of this array, you can use the print_r() function to output the array. The output results are as follows:
Code:
Array
(
[type] => human
[name] => hanguofeng
[age] => 20
)
Then let's serialize it. The serialization 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 it. The output result is:
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), which has three built-in objects (3)
The part inside the braces is a comma-separated list of object expressions. Taking s:4:"type" as an example, it represents a string (s) with a length of 4 digits (4) and a value of "type", that is The key of the first element of the hash array.
We will not go into details in the following parts. You can try to serialize various objects yourself and see how the serialized string is constructed.
Let's look at the deserialization of the array, that is, restoring the serialized string we generated above into 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";}';
$animal = unserialize($animal_ser);
print_r($animal);
?>
In the first line, we assume that the value of $animal_ser is the serialized string obtained above. In the second line, the string is restored to the starting array and assigned to $animal. Finally, the $animal array is output. At this time The output is the same as the original array output at the beginning of this section, that is:
code:
Array
(
[type] => human
[name] => hanguofeng
[age] => 20
)
In this way we have completed the deserialization of the array.
Expand knowledge - Serialization and deserialization of custom objects
Serializing arrays is a basic operation. However, in actual programming, we may often serialize other types of variables, such as Custom objects are serialized. Here is a class A written by ourselves (saved in classa.inc):
Code:
<?php
class A {
var $one = 1;
function show_one() {
echo $this->one;
}
}
?>
We create an instance of the class and serialize the instance in the following code:
Code:
<?php
include("classa.inc");
$a=new A;
echo(serialize($a));
?>
The output content at this time is:
code:
O:1:"A":1:{s:3:"one";i:1;}
Overall, this serialized string outputs the current state of the object, that is, the value of i is 1. Let's analyze the details one by one. O:1: Since the current variable is a custom object, the characterizing character is "O", which means Object. The following "A" identifies which class the variable is an instance of, here it is class A. Inside the curly brackets are the names and values of each attribute of the instance. Then we deserialize it:
Code:
<?php
include("classa.inc");
$s = 'O:1:"A":1:{s:3:"one";i:1;}';
$a = unserialize($s);
$a->show_one();
?>
At this time, "1" is output, that is, the show_one() method of class A is called. You can notice that although the serialized string of the instance does not contain the class method, we can still call the class method after we deserialize it. This feature is supported in PHP4 and above (of course , you need to include the class definition file classa.inc).
Note: You can refer to the Language Reference->Classes and Objects->Serializing objects - objects in sessions section of the PHP manual.
Serializing to JSON in JavaScript—using json2.js
There is no built-in method to serialize objects directly in JavaScript. Of course you can write one yourself, but I still strongly recommend that you be lazy here and use ready-made components. JSON's official website www.json.org provides a code library for JSON serialization of JavaScript objects - json2.js, which you can get from here.
After obtaining the json2.js file, you can open this file. The first part of the file contains a considerable amount of comment information. If your English is good enough, you can omit this section and just refer to the comments of the file. Okay, if as a programmer, you have seen enough letters and want to see my Chinese characters + letters, then you can continue down.
Simply translate this comment: Please refer to http://www.JSON.org/js.html. This file creates a global object JSON containing two methods. Its methods are:
Code:
JSON.stringify(value, whitelist)
value any JavaScript value, usually an object or array
whitelist An optional array parameter used to determine how the object value is serialized. This method generates JSON text from a JavaScript value. When serializing, there are three possibilities based on the optional parameter whitelist:
If an object has a toJSON method, then call this method and the return value of the toJSON method will be serialized.
Otherwise, if the optional whitelist parameter is an array, the elements in the array will be used to select the members of the object for serialization.
Otherwise, if the whitelist parameter is not used, all members of the object will be serialized.
If a value has no JSON representation, such as undefined or a function, it will not be serialized. In objects, such values will be ignored, and in arrays they will be replaced by null.
JSON.stringify(undefined) will return undefined. The date will be serialized to the quoted ISO date.
Example:
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 filters and transforms the 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 is unchanged. If it returns undefined, the member will be deleted.
Example:
code:
//Parse the text and if a key contains the string "date", convert its value to a date
myData = JSON.parse(text, function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value;
});
The above introductory tutorial has given you a basic understanding of how to use json2.js. I will not go into details about this file here. I just have a small tip. If you want to simply parse a JSON text, you can use eval() Function, the function is a built-in function of JavaScript. For example, to parse the JSON text generated in the case of JSON.stringify, you can use:
code:
var myE = eval('["e",{"pluribus":"unum"}]');
to get the object myE.
Serialize to JSON in JavaScript—use prototype.js
If you are like me and like to use open source JavaScript frameworks in your projects, then you may be able to skip using the json2.js file. Here prototype.js is For example, this file can be downloaded at http://www.prototypejs.org . Since this article is not about the JavaScript framework, I assume here that you already have some understanding of the use of prototype.js.
prototype.js provides the toJSON method for Object objects. You can use the Object.toJSON() method to achieve serialization of objects, for example:
code:
var cat=
{
name:"hellokitty",
height:"6 apples"
}
alert(Object.toJSON(cat));
//A dialog box will pop up with the content {"name": "hellokitty", "height": "6 apples"}
In addition, there is additional JSON support in prototype.js, mainly the parsing of the JSON content in the Ajax return request in the Ajax object. This has nothing to do with our content for the time being and will not be introduced again.
PHP and JSON
Above we have learned about the method of object serialization in PHP and the method of serializing objects into JSON in JavaScript. You will probably question why I put the two together, because their syntax is actually is not exactly the same, however, in PHP it is possible to deserialize JSON text, and it is also possible to serialize PHP objects to JSON instead of PHP-style text. This is mainly accomplished by the two functions json_decode and json_encode. It should be noted that these two functions are only supported in PHP 5 >= 5.2.0. If you want to write a program that runs in the PHP4 environment, then 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 PHP variable
parameter
json
JSON encoded text
assoc
When TRUE, the return value is an associative array.
The return value
is an object, or if the optional assoc parameter is TRUE, an associative array will be returned.
json_encode function
syntax
string json_encode (mixed $value)
This function returns a JSON expression
parameter
value
of a value
The value to be encoded can be any type of parameter except resource. This function only works in UTF-8 encoding format.
Return value.
Returns the encoded JSON text on success.
json_decode function instance
The following two examples are based on one of our Scenario assumption, that is, we have a user registration module, which works in an "object-oriented" manner. In the json_decode function instance, we change the user's registration information into a class attribute in the foreground, and then pass it to the background php file (for simplicity, Ajax is not used here). In the json_encode example, we reference a js file in the html file, the address points to the php file, and output the json-encoded user object in the php file (also for simplicity, we directly generate an object without getting the information from the database), and output in html.
Okay, let’s first look at the front-end page json_encode.htm. This page imitates the usual registration page. There is a form on it. When submitted, the JavaScript function is triggered, a user object user is generated, and the form content is set as the user object. Attribute, generate JSON text and pass it to the background json_encode.php file in POST mode. In the js_encode.php file, use the json_decode function to parse the JSON text into a PHP object and output it.
Okay, let’s take a look at the json_encode.html file first. The file code is as follows:
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_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</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 the form is submitted, the JavaScript function JSON_text() will be triggered. This function first creates a JavaScript object user, sets its name, email and password attributes to the values of the corresponding form, and then uses the JSON.stringify method of the json2.js file to It is converted into JSON text json_string, and finally the hidden field is set (to make it clear here, I display this hidden field in the form of a text box) the value of txt_json is json_string, and the form is submitted.
Next go to the json_encode.php file, as follows:
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, first get the value of the POST form field txt_json in the json_encode.html file, put it into the variable $json_string, and then judge that if the current PHP setting is magic_quotes_gpc=On, that is, the incoming double quotes will be converted meaning, so that the json_decode function cannot parse it, so we need to unescape it. Then, use the json_decode function to convert the JSON text into an object, save it in the $user variable, and finally use echo var_dump($user); to dump the object. The final result is:
Code:
object(stdClass)#1 (3) {
["name"]=>
string(10) "hanguofeng"
["email"]=>
string(18) " [email protected] "
["password"]=>
string(10) "hanguofeng"
}
the json_encode function instance
is still composed of two parts, namely json_enode.html and json_encode.php. In the json_decode.html file, the form is basically similar to the json_decode.html file, but the difference is that this time we want to get the JSON text of the corresponding user from the json_encode.php file. Let's look at this PHP file first:
Code:
<?php
Class user{
public $name="";
public $email="";
public $password="";
};
$myUser = new user;
$myUser->name="hanguofeng";
$myUser->email=" [email protected] ";
$myUser->password="hanguofeng";
$json_string = json_encode($myUser);
?>
var user = <?php echo($json_string)?>;
This file first creates the class user, then obtains an instance of the user class myUser, and sets its username, email and password. Then it uses the json_encode function to convert it into JSON text, saves it in the variable $json_string, and finally outputs a piece of JavaScript Code to create the global variable user in JavaScript.
Next, we need to introduce the json_encode.php file into the json_encode.html file and get the various attributes of the user object, as follows:
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</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. The first is that we introduce the json_encode.php file as a JavaScript file with this code:
Code:
<script src="json_encode.php" type="text/javascript"></script>
The second point is:
We add JavaScript code after the text box code, operate the value attribute of the text box, and set its value to the corresponding value of the user object.