search
HomeBackend DevelopmentPHP TutorialApplication of JSON in PHP_PHP Tutorial

Application of JSON in PHP_PHP Tutorial

Jul 15, 2016 pm 01:25 PM
ajaxjsonphpNointernetexistapplicationwhat isof

互联网的今天,AJAX已经不是什么陌生的词汇了。说起AJAX,可能会立即想起因RSS而兴起的XML。XML的解析,恐怕已经不是什么难题了,特别是PHP5,大量的XML解析器的涌现,如最轻量级的SimpleXML。不过对于AJAX来说,XML的解析更倾向于前台Javascript的支持度。我想所有解析过XML的人,都会因树和节点而头大。不可否认,XML是很不错的数据存储方式,但是其灵活恰恰造成了其解析的困难。当然,这里所指的困难,是相对于本文的主角--JSON而言。

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

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

<?php$arr = array(    'name' => '陈毅鑫',    'nick' => '深空',    'contact' => array(        'email' => 'shenkong at qq dot com',        'website' => 'http://www.chenyixin.com',    ));$json_string = json_encode($arr);echo $json_string;?>

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

{"name":"u9648u6bc5u946b","nick":"u6df1u7a7a","contact":{"email":<br>"shenkong at qq dot com","website":"http://www.chenyixin.com"}}

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

<?php$arr = array(    'name' => '陈毅鑫',    'nick' => '深空',    'contact' => array(        'email' => 'shenkong at qq dot com',        'website' => 'http://www.chenyixin.com',    ));$json_string = json_encode($arr);$obj = json_decode($json_string);print_r($obj);?>

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

$json_string = json_encode($arr);$obj = json_decode($json_string);$arr = (array) $obj;print_r($arr);

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

<script type="text/javascript">var arr = {"name":"u9648u6bc5u946b","nick":"u6df1u7a7a","contact":{"<br>email":"shenkong at qq dot com","website":"http://www.chenyixin.com"}};alert(arr.name)</script>

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

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

主调文件index.html:

<script type="text/javascript">function getProfile(str) {    var arr = str;    document.getElementById('nick').innerHTML = arr.nick;}</script><body><div id="nick"></div></body><script type="text/javascript" src="http://www.openphp.cn/demo/<br>profile.php"></script>

被调文件profile.php:

<?php$arr = array(    'name' => '陈毅鑫',    'nick' => '深空',    'contact' => array(        'email' => 'shenkong at qq dot com',        'website' => 'http://www.chenyixin.com',    ));$json_string = json_encode($arr);echo "getProfile($json_string)";?>

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


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446680.htmlTechArticle互联网的今天,AJAX已经不是什么陌生的词汇了。说起AJAX,可能会立即想起因RSS而兴起的XML。XML的解析,恐怕已经不是什么难题了,特别是...
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
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

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

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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