search
HomeBackend DevelopmentPHP TutorialPHP serialization and JSON_PHP tutorial

原文连接:http://hi.baidu.com/lostdays/blog/item/8d76c300ec4e3c15738b65fa.html

总目录

What 、Why、How  

      What   
      Why   
      How  

PHP串行化语法   
      PHP串行化实例   
      在JavaScript中串行化为JSON—使用json2.js   
      在JavaScript中串行化为JSON—使用prototype.js

 PHP与JSON  

json_decode函数   
      json_encode函数   
      json_decode函数实例   
      json_encode函数实例  

实践出真知

背景说明   
      前台JavaScript部分   
      后台PHP部分


What 、Why、How

What

Ok,各位亲爱的朋友,让我们开始这个新概念的旅程,串行化这个话题可能大家以前都没有多加关注,事情其实起源于那天我随便翻翻PHP手册,发现这个串行化的函数,之后闲来无聊又做一个WordPress的插件,这个时候顺便用了一下串行化,发现在某些场合的确非常方便。

先来解释下串行化:简单来说,串行化即将变量转换成字节流的过程。串行化的提出,有效的解决了对象的保存和传输的问题,举例来说,我在JavaScript 中建立了一个对象,我现在想将这个对象保存到服务器端的数据库中,那么我如何进行操作呢,这个时候往往就用到了对象的串行化。在JavaScript的串行化中不得不提JSON,JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写,同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。

人们通常将JSON和XML进行比较,二者都是将对象扁平化(稍后我们解释这个“扁平化”)的一种手段,XML的特点是结构严谨,而JSON的特点则是简单易读、容易使用程序进行分析,因为它能够很简单的将一个对象转换为一个字符流的形式,例如如下代码:

代码:

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

则是一个JSON表达式,他保存了一个对象,我们如何将它恢复为对象呢?很简单,如下:

代码:

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

我们通过JavaScript的求值函数,将JSON表达式进行运算,并返回值,用以获得一个对象,到这里,我想你一定会和我一样,对JSON格式的创造者的思维佩服不已吧。本来说讲串行化的,“不小心”谈到JSON,并且讲了这么多,呵呵,跑题了吗?没有,PHP的串行化和JSON是非常像的,一个PHP的串行化表达式如下:

代码:
a:3:{s:4:"type";s:5:"human";s:4:"name";s:10:"hanguofeng";s:3:"age";s:2:"20";}
他看起来结构和JSON有些类似,实际上,这个表达式是如下数组的串行化结果:
代码:
$animal =
array
(
"type" => "human",
"name" => "hanguofeng",
"age"   => "20"
);
OK,上面的一些介绍只是让你大致看到串行化和JSON是什么样的东西,你无须对这里的代码过分纠结,我们在后面会详细讲解的,下面我们来谈谈为什么要使用串行化。

Why

串行化首先是作为数据传输的方便而出现的,正如本文开始我提出的问题,我在JavaScript中建立了一个对象,我现在想将这个对象保存到服务器端的数据库中,应该如何做,这其实上是一个“我如何将一个对象从浏览器提交到服务器”的问题,在这个传输过程中,我们知道,实际上只能够传递字符流,字符流是一维(扁平)的,然而很多对象却是多维的,如果要传递的对象是一个字符串,那么很简单,我们直接将其作为传递的内容就可以了,如果要传递的对象是一个数组或者其他的结构呢,我们就需要用字符流来描述他,就比如在电话里面,我问你的名字是什么,你会告诉我,你的名字是张三、李四,而我问你,你的长相如何呢,你就需要用文字向我描述了,我们进行数据传递的媒介往往和这条电话线路一样,只能传递字符流,而我们描述对象的过程,实际上就是串行化的过程。

另外,串行化也可以用于对对象的持久化存储,也许你曾经也和我一样,想着在数据库的某一个字段中存储一个对象,现在我们可以非常简单的做到这一点,并且,你的这个数据库字段不需要设定为特殊格式,设定为 varchar就可以了(当然,如果对象很大,你可能需要设定为text)。

How

PHP串行化语法

好了,我想What和Why的问题你都了解了,本节最后我们来讲点理论性强一些的内容,就是如何使用PHP串行化和反串行化数据,如何将JavaScript对象串行化(即变为JSON格式)和如何将其反串行化,最后则是如何将JSON和PHP的串行化建立关系。

PHP为我们提供了两个函数,用来进行串行化和反串行化的操作,这两个函数分别是:serialize()和unserialize(),他们适用于PHP4和PHP5,下面分别进行讲解:

serialize()

(PHP 4, PHP 5, PECL axis2:0.1.0-0.1.1)
serialize — 获得一个可存储的表述值

说明

string serialize ( mixed $value )
获得一个可存储的表述值
本函数用于无损的存储或者传递PHP变量值和结构。
如果需要将已经串行化的值转回PHP变量,可以使用unserialize()函数。

参数

value
即被串行化的表达式。serialize()处理除资源指针之外的所有类型,你甚至可以将含有指向自身元素的数组串行化。你串行化的含有循环指向的数组或者对象一样会被存储,其他的指向则会丢失。
当串行化对象时,PHP会尝试首先调用其成员函数__sleep()。这将允许对象在被串行化之前进行诸如最后的清理工作等。同样地,当使用unserialize()函数将对象恢复时,会调用成员函数__wakeup()。

返回值

   返回一个可以被存储在任何地点的包含对象的字节流表达式的字符串。

unserialize()

(PHP 4, PHP 5, PECL axis2:0.1.0-0.1.1)
unserialize — 从一个已存储的表达式中获得一个PHP变量值

说明

mixed unserialize ( string $str )
unserialize()获取一个简单类型的串行化变量并将其转换回PHP变量值。

参数

str

   串行化后的字符串
如果被反串行化的变量是一个对象,则成功恢复该对象的结构后,PHP将自动尝试执行该对象的__wakeup()成员函数(如果其存在)。
unserialize_callback_func 指令:你可以设定在此过程中呗执行的回调函数,如果某个未被定义的类应当在反串行化时被实例化(以避免获得一个不完全的对象 “__PHP_Incomplete_Class”)。你可以使用php.ini,ini_set()或者.htaccess来定义 “unserialize_callback_func”。当一个未被定义的类被实例化时,它会被调用。屏蔽这个特性只需将其设为空即可。

返回值

返回转换后的数值,可能是布尔变量、实数、浮点数、字符串、数组或者对象。
假如传入的字符串不可以被反串行化,则返回FALSE,同时抛出NOTICE错误。
(以上译自PHP手册)

PHP串行化实例

数组的串行化和反串行化

OK,让我们来用实例学习一下,首先,请建立sample1.php文件,我们在这个文件中用如下语句来创建一个哈希数组:

代码:
$animal =
array
(
"type" => "human",
"name" => "hanguofeng",
"age"   => "20"
);
?>
为了测试这个数组的值,你可以使用print_r()函数来输出数组,输出的结果如下:

代码:
Array
(
[type] => human
[name] => hanguofeng
[age] => 20
)
那么我们将他来串行化一下,串行化的代码如下:

Code:
$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 analyze this string:
a:3 means that this is an array object (a), which has three built-in Object (3)
The part inside the curly brackets 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). The value is "type", which is the key of the first element of the hash array.
The following parts are analogous, so we won’t go into details. 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:
$animal_ser=a:3:{s:4:"type";s:5:"human";s:4:"name";s:10 :"hanguofeng";s:3:"age";s:2:"20";};

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486569.htmlTechArticleOriginal link: http://hi.baidu.com/lostdays/blog/item/8d76c300ec4e3c15738b65fa.html General Catalog What, Why, How What Why How How PHP serialization syntax PHP serialization example serialization in JavaScript...

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor