Home php教程 php手册 正确掌握PHP JSON应用

正确掌握PHP JSON应用

Jun 13, 2016 am 11:10 AM
json php xml and application master yes correct node parse

我想所有解析过XML的人,都会因树和节点而头大。不可否认,XML是很不错的数据存储方式,但是其灵活恰恰造成了其解析的困难。当然,这里所指的困难,是相对于本文的主角--PHP JSON应用而言。

JSON为何物?我就不重复概念了。通俗的说,它是一种数据的存储格式,就像PHP序列化后的字符串一样。它是一种数据描述。比如我们将一个数组序列化后存放,就可以很容易的反序列化后应用。JSON也是如此,只不过他搭建的是客户端Javascript和服务端PHP的交互桥梁。我们用PHP生成JSON后的字符串,然后把这个字符串传给前台Javascript,Javascirpt就可以很容易的将其反JSON然后应用。说通俗点,它真的很像数组。

言归正传,如何正确掌握PHP JSON应用。PHP5.2开始内置了JSON的支持。当然,如果低于这个版本的话,那么市面上有很多PHP版本的实现,随便下一个用就OK啦。现在主要是说说PHP内置支持的JSON。很简单,两个函数:json_encode和json_decode(跟序列化很像啦)。一个编码,一个解码。先看看编码的使用:

<ol class="dp-xml">
<li class="alt"><span><span>$</span><span class="attribute">arr</span><span> = </span><span class="attribute-value">array</span><span>(   </span></span></li>
<li>
<span>'name' =</span><span class="tag">></span><span>'陈毅鑫',   </span>
</li>
<li class="alt">
<span>'nick' =</span><span class="tag">></span><span> '深空',   </span>
</li>
<li>
<span>'contact' =</span><span class="tag">></span><span> array(   </span>
</li>
<li class="alt">
<span>'email' =</span><span class="tag">></span><span> 'shenkong at qq dot com',   </span>
</li>
<li>
<span>'website' =</span><span class="tag">></span><span> <br>'http://www.chenyixin.com',   </span>
</li>
<li class="alt"><span>)   </span></li>
<li><span>);   </span></li>
<li class="alt">
<span>$</span><span class="attribute">json_string</span><span> = </span><span class="attribute-value">json_encode</span><span>($arr);   </span>
</li>
<li><span>echo $json_string;   </span></li>
<li class="alt">
<span class="tag">?></span><span> </span>
</li>
</ol>
Copy after login

很简单的将一个数组JSON了。需要指出的是,在非UTF-8编码下,中文字符将不可被encode,结果会出来空值,所以,如果你使用gb2312编写PHP代码,那么就需要将包含中文的内容使用iconv或者mb转为UTF-8再进行json_encode,上面输出结果如下:

<ol class="dp-xml"><li class="alt"><span><span>{"name":"u9648u6bc5u946b"<br>,"nick":"u6df1u7a7a","<br>contact":{"email":"shenkong <br>at qq dot com","website":<br>"http://www.chenyixin.com"}}  </span></span></li></ol>
Copy after login

我都说了和序列化很像,你还不信。编码后就要解码,PHP提供了相应的函数json_decode,json_decode执行后,将会得到一个对象,操作如下:

<ol class="dp-xml">
<li class="alt"><span><span>$</span><span class="attribute">arr</span><span> = </span><span class="attribute-value">array</span><span>(   </span></span></li>
<li>
<span>'name' =</span><span class="tag">></span><span>'陈毅鑫',   </span>
</li>
<li class="alt">
<span>'nick' =</span><span class="tag">></span><span> '深空',   </span>
</li>
<li>
<span>'contact' =</span><span class="tag">></span><span> array(   </span>
</li>
<li class="alt">
<span>'email' =</span><span class="tag">></span><span> 'shenkong<br> at qq dot com',   </span>
</li>
<li>
<span>'website' =</span><span class="tag">><br></span><span> 'http://www.chenyixin.com',   </span>
</li>
<li class="alt"><span>)   </span></li>
<li><span>);   </span></li>
<li class="alt">
<span>$</span><span class="attribute">json_string</span><span> = <br></span><span class="attribute-value">json_encode</span><span>($arr);   </span>
</li>
<li>
<span>$</span><span class="attribute">obj</span><span> = </span><span class="attribute-value">json_decode</span><span>($json_string);   </span>
</li>
<li class="alt"><span>print_r($obj);   </span></li>
<li>
<span class="tag">?></span><span> </span>
</li>
</ol>
Copy after login

访问对象内的属性会吧?$obj->name,这样子的,当然,也可以把它转位数组,方便调用啦:

<ol class="dp-xml">
<li class="alt"><span><span>$</span><span class="attribute">json_string</span><span> = </span><span class="attribute-value">json_encode</span><span>($arr);   </span></span></li>
<li>
<span>$</span><span class="attribute">obj</span><span> = </span><span class="attribute-value">json_decode</span><span>($json_string);   </span>
</li>
<li class="alt">
<span>$</span><span class="attribute">arr</span><span> = (array) $obj;   </span>
</li>
<li><span>print_r($arr);  </span></li>
</ol>
Copy after login

PHP转来转去的用途不是特别大,除了缓存生成,感觉还不如直接存数组呢,不过,当你和前台交互的时候,它的作用就出来咯,下面看看我怎么用Javascript来使用这段字符:

上面中,直接将这个字符串赋给一个变量,它就变成一个Javascript数组了(专业化术语应该不叫数组,不过由于PHP的习惯问题,我就一直叫数组好了,方便理解)。这样,可以很方便的对arr进行遍历或者任意做你想做的事情了。写到这里,好像都没提到AJAX哦?是哦,联想一下,如果服务端返回的responseText用JSON过的字符串代替XML的话,前台Javascript处理起来是不是很方便呢?狗皮膏药就是这样用的。

其实写到这里,除了数据的存储格式不太一样外,JSON和XML也没什么太大区别哦,不过下面我说的一点。虽然和XML没多大关系,不过,可以说明PHP JSON应用拥有更大范围的应用,那就是,跨域的数据调用。由于安全性问题,AJAX不支持跨域调用,这样要调用不同域名下的数据,很麻烦哦,虽然有解决方案(stone在他的讲座上提到过了代理啊什么的虽然听不懂但是知道能解决)。我写两个文件,足以展示跨域调用了。

主调文件index.html

被调文件profile.php

<ol class="dp-xml">
<li class="alt"><span><span>$</span><span class="attribute">arr</span><span> = </span><span class="attribute-value">array</span><span>(   </span></span></li>
<li>
<span>'name' =</span><span class="tag">></span><span> '陈毅鑫',   </span>
</li>
<li class="alt">
<span>'nick' =</span><span class="tag">></span><span> '深空',   </span>
</li>
<li>
<span>'contact' =</span><span class="tag">></span><span> array(   </span>
</li>
<li class="alt">
<span>'email' =</span><span class="tag">></span><span> <br>'shenkong at qq dot com',   </span>
</li>
<li>
<span>'website' =</span><span class="tag">></span><span> <br>'http://www.chenyixin.com',   </span>
</li>
<li class="alt"><span>)   </span></li>
<li><span>);   </span></li>
<li class="alt">
<span>$</span><span class="attribute">json_string</span><span> = </span><span class="attribute-value">json_encode</span><span>($arr);   </span>
</li>
<li><span>echo "getProfile($json_string)";   </span></li>
<li class="alt">
<span class="tag">?></span><span> </span>
</li>
</ol>
Copy after login

很显然,当index.html调用profile.php时,JSON字符串生成,并作为参数传入getProfile,然后将昵称插入到div中,这样一次跨域数据交互就完成了,是不是特别简单。既然PHP JSON应用这么简单易用而且好用,还等什么呢?


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

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

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 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.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles