Home Backend Development PHP Tutorial PHP serialize & JSON 解析

PHP serialize & JSON 解析

Jun 23, 2016 pm 02:32 PM

对于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建构于两种结构:

“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。

值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。


PHP的serialize是将变量序列化,返回一个具有变量类型和结构的字符串表达式,
说起来两者都是以一种字符串的方式来体现一种数据结构,那它们之间有什么区别呢。

先从JSON说起,看一个简单的实例。
例一:

var  test  =  { " Name " : " Peter " , " Age " : 20 };
document.write(test.Name  +   " :  "   +  test.Age);

显示结果:

Peter:  20

变量test中{"Name":"Peter","Age":20}为一个有2个元素的对象(感觉就像PHP的数组):
Name为Peter,Age为20。

当然也可以变得复杂些。
例二:

var  test  =  { " User " :{ " Name " : " Peter " , " Age " : 20 }, " Company " : " FORD " };
document.write(test.User.Name  +   " :  "   +  test.Company);

显示结果:

Peter: FORD

这个例子中User元素中包含了Name和Age。

如果要体现多个User,则需要使用数组,区别于对象的"{}",数组使用"[]"。
例三:

var  test  =  [
                 { " User " :{ " Name " : " Peter " , " Age " : 20 }, " Company " : " FORD " },
                 { " User " :{ " Name " : " Li Ming " , " Age " : 20 }, " Company " : " Benz " }
              ];
document.write(test[ 1 ].User.Name  +   " :  "   +  test[ 1 ].Company);
// 或者使用:document.write(test[1]["User"]["Name"] + ": " + test[1]["Company"]);

显示结果:

Li Ming: Benz


通过以上简单实例就能将一些复杂数据通过一个字符串来进行传递,再配合上Ajax的确是方便很多。
下面再来看看PHP的serialize函数的作用。
例四:

$arr   =   array
       (
           ' Peter ' =>   array
          (
             ' Country ' => ' USA ' ,
             ' Age ' => 20
          ) ,
           ' Li Ming ' =>   array
          (
              ' Country ' => ' CHINA ' ,
              ' Age ' => 21
          )
        );

$serialize_var   =   serialize ( $arr );
echo   $serialize_var ;

显示结果:

a : 2 : {s : 5 : " Peter " ;a : 2 : {s : 7 : " Country " ;s : 3 : " USA " ;s : 3 : " Age " ;i : 20 ;}s : 7 : " Li Ming " ;a : 2 : {s : 7 : " Country " ;s : 5 : " CHINA " ;s : 3 : " Age " ;i : 21 ;}}

这个结果看上去比JSON要复杂一些,其实也很简单,它说明的就是一些数据类型和结构。
以a:2:{s:7:"Country";s:3:"USA";s:3:"Age";i:20;}为例:
      a:2说明这是个有两个元素的数组(array),
      s:7:"Country";s:3:"USA";为第一个元素,s:7说明这是有7个字符的字符串(string),
      后面i:20;也应该猜得到是整数(integer)20。

再来看一下这个例子,
例五:

class  test
{
     var   $var   =   0 ;
     function  add(){
       echo   $var + 10 ;
    }
}

$unserialize_var   =   new  test;
$serialize_var   =   serialize ( $unserialize_var );
echo   $serialize_var ;
$unserialize_var   =   null ;
$unserialize_var   =   unserialize ( $serialize_var );
$unserialize_var -> add();

显示结果:

O : 4 : " test " : 1 : {s : 3 : " var " ;i : 0 ;}
10

从这个例子中可以看出来,serialize对数据的类型和结构都进行的保存,
unserialize后的变量仍然可以使用add()方法。

那么PHP和JSON有没有联系呢,熟悉PHP的朋友应该了解PHP5.2.0已经将JSON extension设置为默认组件,也就是说我们可以在PHP中进行JSON操作,其函数为json_encode和json_decode。
例六:

$arr   =   array
       (
           ' Name ' => ' Peter ' ,
           ' Age ' => 20
       );

$jsonencode   =  json_encode( $arr );
echo   $jsonencode ;

显示结果:

{ " Name " : " Peter " , " Age " : 20 }

这个结果和例一中test值是一样的,通过json_encode将PHP中的变量转换为JSON字符出表达式。
再来看看json_decode的用法。
例七:

$var   =   ' {"Name":"Peter","Age":20} ' ;
$jsondecode   =  json_decode( $var );
print_r ( $jsondecode );

显示结果:

stdClass  Object  ( [Name]  =>  Peter [Age]  =>   20  )

这的确验证了,在JSON中{"Name":"Peter","Age":20}是一个对象,但是在PHP中也可以将其转为数组,在json_decode中将ASSOC参数设置为True即可。
例八:

$var   =   ' {"Name":"Peter","Age":20} ' ;
$jsondecode   =  json_decode( $var , true );
print_r ( $jsondecode );

显示结果:

Array  ( [Name]  =>  Peter [Age]  =>   20  )


另,需要注意的是JSON是基于Unicode格式,所以要进行中文操作要将其转化为UTF-8格式。
通过上面这些例子相信大家对于JSON和PHP的serialize、json_encode都有了初步了解,
结合PHP、Javascript、JSON以及Ajax就可以完成强大的数据交互功能。

相关参考资料:
PHP JSON Functions: http://cn.php.net/manual/en/ref.json.php
JSON Introduction:http://www.json.org/json-zh.html
网友实例: http://www.only4.cn/archives/95
             http://www.openphp.cn/blog.php?blog_id=12

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

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.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 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.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

See all articles