PHP processing JSON Format Data Classic case summary, JSON classic case _php Tutorial

Source: Internet
Author: User
Tags php json javascript array

PHP processing JSON Format Data Classic case summary, JSON classic case


This paper summarizes how PHP handles JSON-formatted data. Share to everyone for your reference, as follows:

1.json Introduction:

What is JSON?

Simply put, JSON can convert a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or in an asynchronous application passing a string from a WEB client to a server-side program.

In layman's words, it is a storage format for data, just like a string after PHP serialization.

It is also a data description, such as: We put an array after the storage, it can be easily deserialized after the application; JSON is the same, but it is the client JavaScript and server-side PHP interaction bridge.

How do I use JSON?

JSON support is built into the version since php5.2, and there are two main functions:

Json_encode (): Encode, generate a JSON string
Json_decode (): A decoding

Note: after encoding the Json_encode () function, a JSON-formatted string is returned, such as: $json = ' {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4, ' E ': 5} '; Will get a JSON-formatted JavaScript object

2.json Case One:

Use of Json_encode:

<?php$arr = Array (' name ' = ' = ' Wei Yanhui ', ' nick ' = ' = ' for the dream to soar, ' contact ' = ' + ' = ' email ' = ' = ' zhuoweida@163.com ', ' W Ebsite ' + ' http://zhuoweida.blog.tianya.cn ',)); $json _string = Json_encode ($arr); Echo $json _string;//json-formatted string? >

Results:

{   "name": "\u9648\u6bc5\u946b",   "Nick": "\u6df1\u7a7a",   "contact":       {         "e-mail": "Shenkong at QQ" Dot com ",         " website ":" Http:\/\/www.chinaz.com "       }}

Hint: the output of the data itself is a JSON-formatted JS object, because there is no quotation marks, so the foreground page can be directly used as a JSON object

Summary: associative arrays are constructed according to JavaScript objects

Analysis: The above example is a simple json of an array, it should be pointed out that in the non-Utf-8 encoding, the Chinese characters will not be encode, the result will be null, so if you use gb2312 encoding to write PHP code, Then you need to convert content containing Chinese into utf-8 after using Iconv or MB series functions in Json_encode

3.json Case Two:

Use of Json_decode:

<?php$arr = Array (' name ' = ' = ' Wei Yanhui ', ' nick ' = ' for Dream soar ', ' contact ' = ' + ' array (' email ' = ' zhuoweida@163.com ', ' Website ' = ' http://zhuoweida.blog.tianya.cn ',); $json _string = Json_encode ($arr); $obj = Json_decode ($json _string ); You can use $obj->name to access the properties of an object $arr=json_decode ($json _string,true);//Convert the second argument to true when converting to an array print_r ($obj);p rint_r ($arr); >

Results:

{   "name": "\u9648\u6bc5\u946b",   "Nick": "\u6df1\u7a7a",   "contact":       {        "e-mail": "Shenkong at QQ" Dot com ",        " website ":" Http:\/\/www.chinaz.com "       }}

Summary: associative arrays are constructed according to JavaScript objects

Hint: the output of the data itself is a JSON-formatted JS object, because there is no quotation marks, so the foreground page can be directly used as a JSON object

parsing: decoding after encoding, PHP provides the corresponding function Json_decode, after executing this function, you will get an object or an array.

4.json Case Three:

When interacting with the foreground, the JSON function is displayed:

For example, the JavaScript code is as follows:

Code Analysis: The above code, directly to the JSON format data assigned to a variable, it becomes a JavaScript object, so that we can easily traverse the obj

tip: in JavaScript, access to an array is accessed through an index, and access to object properties is accessed through the object name. Property name.

Hint: the output of the data itself is a JSON-formatted JS object, because there is no quotation marks, so the foreground page can be directly used as a JSON object

5.json case FOUR: JSON cross-domain data invocation:

Example: Keynote file index.html

   

For example: called File profile.php

<?php$arr = Array (  ' name ' = ' = ' Wei Yanhui ',    ' nick ' = ' dream soar ', ' contact ' = ' + '     array (         ' email ' = ') ' Zhuoweida@163.com ',         ' website ' = ' http://zhuoweida.blog.tianya.cn ',      )    ); $json _string = Json_encode ($arr); echo "GetProfile ($json _string)";? >

Code Analysis: when index.html invokes the Profile.php,json string generation and passes in the GetProfile as a parameter, then inserts the nickname into the Div so that the cross-domain data interaction is completed

6.js How to parse the JSON string returned by the server side?

When we use AJAX for client-server interaction, without the framework such as jquery, the general practice is to have the server return a JSON string and then parse it into a JavaScript object on the client side. The method used for parsing is usually eval or new function, and currently IE8 and firefox3.1 have native JSON objects built into them.

Example 1:

var strtest= ' {' A ': ' B '} '; Convert to JS object var obj=eval ("(" +strtest+ ")");

Example 2:

function Strtojson (strtest) {  json.parse (str);}

7. Case five: JSON of objects

<?php//1. Object class jsontest{  var $id = 1;  var $name = ' Heiyeluren ';  $gender = ' Male ';} $obj = new Jsontest;echo Json_encode ($obj). "
";? >

The results of the browser output:

{  "id": 1,  "name": "Heiyeluren",  "gender": "\u7537"}

Conclusion: The JSON string of an object is constructed according to the JavaScript object. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above example is a simple json of an array, it should be pointed out that in the non-Utf-8 encoding, the Chinese characters will not be encode, the result will be null, so if you use gb2312 encoding to write PHP code, Then you need to convert content containing Chinese into utf-8 after using Iconv or MB series functions in Json_encode

Hint: the output of the data itself is a JSON-formatted JS object, because there is no quotation marks, so the foreground page can be directly used as a JSON object

8. Case SIX: JSON of indexed arrays

<?PHP$ARR1 = Array (1, ' heiyeluren ', ' Male '), Echo Json_encode ($arr 1). "
";? >

The results of the browser output:

[  1,  "Heiyeluren",  "\u7537"]

conclusion: JSON strings for a purely numeric indexed array are stored in an array that JavaScript recognizes, rather than as objects that JavaScript can recognize. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above example is a simple json of an array, it should be pointed out that in the non-Utf-8 encoding, the Chinese characters will not be encode, the result will be null, so if you use gb2312 encoding to write PHP code, Then you need to convert content containing Chinese into utf-8 after using Iconv or MB series functions in Json_encode

9. Case seven: JSON of associative arrays

<?PHP$ARR2 = Array ("id" =>1, "name" = = ' Heiyeluren ', "gender" = "male"); Echo Json_encode ($arr 2). "
";? >

The results of the browser output:

{  "id": 1,  "name": "Heiyeluren",  "gender": "\u7537"}

conclusion: JSON strings associated with indexed arrays are constructed in the form of JavaScript objects. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above example is a simple json of an array, it should be pointed out that in the non-Utf-8 encoding, the Chinese characters will not be encode, the result will be null, so if you use gb2312 encoding to write PHP code, Then you need to convert content containing Chinese into utf-8 after using Iconv or MB series functions in Json_encode

Hint: the output of the data itself is a JSON-formatted JS object, because there is no quotation marks, so the foreground page can be directly used as a JSON object

10. Case eight: JSON of a multidimensional indexed array

<?PHP$ARR3 = Array (Array (1, ' heiyeluren ', ' Male '), array (1, ' heiyeluren ', ' Male ')), Echo Json_encode ($arr 3). "
";? >

The results of the browser output:

[  1, "Heiyeluren", "\u7537"],  [1, "Heiyeluren", "\u7537"]]

conclusion: JSON strings for multidimensional numeric indexed arrays are stored in arrays that JavaScript can recognize. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above example is a simple json of an array, it should be pointed out that in the non-Utf-8 encoding, the Chinese characters will not be encode, the result will be null, so if you use gb2312 encoding to write PHP code, Then you need to convert content containing Chinese into utf-8 after using Iconv or MB series functions in Json_encode

tip: The output data can be used directly as a JavaScript array

11. Case NINE: JSON for multidimensional associative arrays

<?PHP$ARR4 = Array (  "id" =>1, "name" = = ' Heiyeluren ', "gender" = ' man '),  array ("id" =>1, " Name "= = ' Heiyeluren '," gender "=" male "); Echo Json_encode ($arr 4)."
";? >

The results of the browser output:

[  {"id": 1, "name": "Heiyeluren", "Gender": "\u7537"},  {"id": 1, "name": "Heiyeluren", "Gender": "\u7537"}]

Conclusion: the multidimensional associative index array is a JavaScript array in the periphery, and the intermediate index array is the object. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above example is a simple json of an array, it should be pointed out that in the non-Utf-8 encoding, the Chinese characters will not be encode, the result will be null, so if you use gb2312 encoding to write PHP code, Then you need to convert content containing Chinese into utf-8 after using Iconv or MB series functions in Json_encode

tip: The output data can be used directly as a JavaScript array

12. Case 10: Creation of a JSON-formatted JavaScript object

The format and syntax of JSON:

var jsonobject={    //The attribute syntax within an object (property name and property value are paired)    Propertyname:value,    //function syntax within the object (function names and functions are paired)    Functionname:function () {...;};

Attention:

①jsonobject--JSON object name
②propertyname--Property name
③functionname--Function name
④ a pair of curly braces that enclose multiple names/values in a collection
The ⑤ property name or function name can be any string, even an empty string
⑥ comma is used to separate each pair of "name/value" pairs

Tips:

① in JavaScript, access to an array is accessed through an index, and access to object properties is accessed through the object name. Property name.
② after Json_encode () data are JS can recognize the format, and after the Json_decode () data is the format that PHP can recognize, it is clear to everyone
③ through Json_encode () and output data are JSON-formatted JavaScript objects, in the foreground can be directly used as a JS object

In addition, the site also provides the following format and conversion tools to facilitate the use of:

PHP Code online format Beautification tool:
Http://tools.jb51.net/code/phpformat

Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson

JavaScript code beautification/compression/formatting/encryption Tools:
Http://tools.jb51.net/code/jscompress

Online XML format/compression tool:
Http://tools.jb51.net/code/xmlformat

More about PHP related content readers can view the topic: "PHP JSON Format data Operation skills Summary", "PHP file Operation Summary", "PHP operation and operator Usage Summary", "PHP Network Programming Skills Summary", "PHP Basic Grammar Introductory Tutorial", " PHP Operations Office Documentation Tips Summary (including word,excel,access,ppt), PHP date and Time usage summary, PHP Object-oriented Programming primer tutorial, PHP string Usage Summary, php+ MySQL database operation Getting Started tutorial and PHP Common database operation Skills Summary

I hope this article is helpful to you in PHP programming.

http://www.bkjia.com/PHPjc/1127842.html www.bkjia.com true http://www.bkjia.com/PHPjc/1127842.html techarticle PHP processing JSON Format Data Classic case summary, JSON classic example This article summarizes the way PHP handles JSON-formatted data. Share to everyone for your reference, as follows: 1.json introduction ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.