search
Homephp教程php手册PHP中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建构于两种结构:

“名称/值”对的集合(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说起,看一个简单的实例。

程序1:

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。

当然也可以变得复杂些:

程序2:

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

显示结果:

Peter: FORD

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

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

程序3:

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函数的作用。

程序4:

$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。

再来看一下这个例子:

程序5:

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。

程序6:

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

显示结果:

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

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

再来看看json_decode的用法。

程序7:

$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即可。

程序8:

$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就可以完成强大的数据交互功能。

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

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.