Home php教程 php手册 PHP串行化与JSON

PHP串行化与JSON

Jun 13, 2016 am 10:36 AM
http json php and connect

原文连接: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
)
那么我们将他来串行化一下,串行化的代码如下:

代码:
$animal =
array
(
"type" => "human",
"name" => "hanguofeng",
"age"   => "20"
);
$animal_ser=serialize($animal);
echo($animal_ser);
?>
这里我们将数组$animal串行化,将返回的串行化字符串保存在变量$animal_ser中,并输出,输出的结果是:

代码:
a:3:{s:4:"type";s:5:"human";s:4:"name";s:10:"hanguofeng";s:3:"age";s:2:"20";}
我们来简单对这个字符串进行一个解析:
a:3表示这是一个数组型的对象(a),他共有三个内置的对象(3)
大括号里面的部分是以逗号分割的对象表达式列表,以s:4:"type"为例,他表示一个字符串(s),长度为4位(4),值为“type”,即哈希数组的第一个元素的键。
后面的部分以此类推,我们不再赘述,你可以试试自己将各种对象串行化,看看串行化后的字符串是如何构建的。
下面来看数组的反串行化,即将我们上面生成的串行化字符串恢复为数组,代码如下:

代码:
$animal_ser=a:3:{s:4:"type";s:5:"human";s:4:"name";s:10:"hanguofeng";s:3:"age";s:2:"20";};

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles