PHP和JSON

Jun 23, 2016 pm 02:36 PM

互联网的今天,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(跟序列化很像啦)。一个编码,一个解码。先看看编码的使用:

$arr = array(  

    'name' => '陈毅鑫',  

    'nick' => '深空',  

    'contact' => array(  

        'email' => 'shenkong at qq dot com',  

        'website' => 'http://www.itrenjia.com',  

    )  

);  

$json_string = json_encode($arr);  

echo $json_string;  

?> 

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

{"name":"\u9648\u6bc5\u946b","nick":"\u6df1\u7a7a","contact":{"email":"shenkong at qq dot com","website":"http:\/\/www.itrenjia.com"}} 

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

$arr = array(  

    'name' => '陈毅鑫',  

    'nick' => '深空',  

    'contact' => array(  

        'email' => 'shenkong at qq dot com',  

        'website' => 'http://www.itrenjia.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> </script>

var arr = {"name":"\u9648\u6bc5\u946b","nick":"\u6df1\u7a7a","contact":{"email":"shenkong at qq dot com","website":"http:\/\/www.itrenjia.com"}};  

alert(arr.name)  

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

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

主调文件index.html

<script> </script>

function getProfile(str) {  

    var arr = str;  

    document.getElementById('nick').innerHTML = arr.nick;  

}  

 

 

<script></script> 

被调文件profile.php

$arr = array(  

    'name' => '陈毅鑫',  

    'nick' => '深空',  

    'contact' => array(  

        'email' => 'shenkong at qq dot com',  

        'website' => 'http://www.itrenjia.com',  

    )  

);  

$json_string = json_encode($arr);  

echo "getProfile($json_string)";  

?> 

很显然,当index.html调用profile.php时,JSON字符串生成,并作为参数传入getProfile,然后将昵称插入到div中,这样一次跨域数据交互就完成了,是不是特别简单。既然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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles