PHP和JSON
互联网的今天,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这么简单易用而且好用,还等什么呢?

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

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.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.
