PHP processing JSON Format Data classic case Summary _php tips

Source: Internet
Author: User
Tags arrays eval numeric php introduction php json php programming javascript array

This example summarizes the way PHP processes data in JSON format. Share to everyone for your reference, specific as follows:

1.json Introduction:

What is JSON?

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

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

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

How do I use JSON?

JSON support is built into the php5.2 and later versions, with a main two functions:

Json_encode (): encoding, generating a JSON string
Json_decode (): A decoding

Note: after the Json_encode () function is encoded, returns a JSON-formatted string such as: $json = ' {' A ': 1, "B": 2, "C": 3, "D": 4, "E": 5} '; string output in JSON format, Will get a JSON-formatted JavaScript object

2.json Case One:

Use of Json_encode:

<?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);
echo $json _string;//json format string
?>

Results:

{
   "name": "\u9648\u6bc5\u946b",
   "Nick": "\u6df1\u7a7a",
   "contact":
       {"
         email": "Shenkong At qq dot com ",
         " website ":" Http:\/\/www.chinaz.com "
       }
}

tip: The output data itself is a JSON-formatted JS object, because there are no quotes, so you can use it directly as a JSON object in the foreground page.

Summary: associative arrays are constructed by JavaScript objects

Analysis: The above case is very simple to json an array, you need to point out that in the Utf-8 encoding, Chinese characters will not be encode, the result will come out null value, so if you use gb2312 code to write PHP code, Then you need to convert the content containing Chinese into utf-8 after using the Iconv or MB series function 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 to array
print_r ($obj)
when the second argument is true; Print_r ($arr);
? >

Results:

{
   "name": "\u9648\u6bc5\u946b",
   "Nick": "\u6df1\u7a7a",
   "contact":
       {"
        email": "Shenkong At qq dot com ",
        " website ":" Http:\/\/www.chinaz.com "
       }
}

Summary: associative arrays are constructed by JavaScript objects

tip: The output data itself is a JSON-formatted JS object, because there are no quotes, so you can use it directly as a JSON object in the foreground page.

Analysis: after encoding to decode, PHP provides the corresponding function Json_decode, after executing this function, will get an object or an array.

4.json Case Three:

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

For example: The JavaScript code is as follows:

<script type= "Text/javascript" >
var obj = {
      "name": "\u9648\u6bc5\u946b",
      "Nick": "\u6df1\u7a7a",
      "Contact":
          {"
           email": "Shenkong at qq dot com",
           "website": "Http:\/\/www.chinaz.com"
          }
     };
     alert (obj.name);
</script>

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 obj

tip: in JavaScript, array access is accessed through the index; Object properties are accessed through the object name. Property name.

tip: The output data itself is a JSON-formatted JS object, because there are no quotes, so you can use it directly as a JSON object in the foreground page.

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

For example: Keynote file 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://localhost/demo/profile.php "></script>

For example: called File profile.php

<?php
$arr = Array (
  ' name ' => ' Wei Yanhui ', '
    Nick ' => ' to hover for dream ',
     ' 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 calls the Profile.php,json string generation and passes in the GetProfile as a parameter, and then inserts the nickname into the Div, the Cross-domain data interaction completes

6.js How do I resolve the JSON string returned by the server side?

When we use AJAX for client and server interaction, it is common practice to have the server side return a JSON string and then parse it into a JavaScript object at the client, without using a framework such as jquery. The method used in parsing is typically eval or new function, whereas currently IE8 and firefox3.1 have built-in 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). " <br/> ";
? >

Browser Output results:

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

Conclusion: the JSON string for an object is constructed from a JavaScript object. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above case is very simple to json an array, you need to point out that in the Utf-8 encoding, Chinese characters will not be encode, the result will come out null value, so if you use gb2312 code to write PHP code, Then you need to convert the content containing Chinese into utf-8 after using the Iconv or MB series function in Json_encode

tip: The output data itself is a JSON-formatted JS object, because there are no quotes, so you can use it directly as a JSON object in the foreground page.

8. Case SIX: JSON of an indexed array

<?php
$arr 1 = array (1, ' heiyeluren ', ' Male ');
Echo Json_encode ($arr 1). " <br/> ";
? >

Browser Output results:

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

Conclusion: the JSON string for a pure numeric index array is stored in an array that is recognizable by JavaScript, rather than as an object that JavaScript can recognize. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above case is very simple to json an array, you need to point out that in the Utf-8 encoding, Chinese characters will not be encode, the result will come out null value, so if you use gb2312 code to write PHP code, Then you need to convert the content containing Chinese into utf-8 after using the Iconv or MB series function in Json_encode

9. Case seven: JSON of associative arrays

<?php
$arr 2 = array ("id" =>1, "name" => ' Heiyeluren ', "gender" => ' Male ');
Echo Json_encode ($arr 2). " <br/> ";
? >

Browser Output results:

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

Conclusion: The JSON string of an associative index array is constructed in the form of a JavaScript object. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above case is very simple to json an array, you need to point out that in the Utf-8 encoding, Chinese characters will not be encode, the result will come out null value, so if you use gb2312 code to write PHP code, Then you need to convert the content containing Chinese into utf-8 after using the Iconv or MB series function in Json_encode

tip: The output data itself is a JSON-formatted JS object, because there are no quotes, so you can use it directly as a JSON object in the foreground page.

10. Case EIGHT: JSON for multidimensional index arrays

<?php
$arr 3 = array (1, ' heiyeluren ', ' Male '), array (1, ' heiyeluren ', ' Male '));
Echo Json_encode ($arr 3). " <br/> ";? >

Browser Output results:

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

Conclusion: The JSON string of the multidimensional numeric index array is stored according to the array that JavaScript can recognize. Unable to recognize Chinese, all Chinese strings are not displayed correctly

Analysis: The above case is very simple to json an array, you need to point out that in the Utf-8 encoding, Chinese characters will not be encode, the result will come out null value, so if you use gb2312 code to write PHP code, Then you need to convert the content containing Chinese into utf-8 after using the Iconv or MB series function in Json_encode

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

11. Case NINE: JSON for multidimensional associative arrays

<?php
$arr 4 = array (
  array ("id" =>1, "name" => ' Heiyeluren ', "gender" => ' Male '),
  array ("id" = >1, "name" => ' Heiyeluren ', "gender" => ' Man ')
);
Echo Json_encode ($arr 4). " <br/> ";
? >

Browser Output results:

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

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

Analysis: The above case is very simple to json an array, you need to point out that in the Utf-8 encoding, Chinese characters will not be encode, the result will come out null value, so if you use gb2312 code to write PHP code, Then you need to convert the content containing Chinese into utf-8 after using the Iconv or MB series function in Json_encode

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

12. Case 10: Creation of a JavaScript object in JSON format

Format and syntax for JSON:

var jsonobject=
{
    //attribute syntax within object (property name and attribute value are in pairs)
    propertyname:value,
    //Object function syntax (functions name and function contents appear in pairs)
    Functionname:function () {...;}
};

Attention:

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

Tips:

① in JavaScript, array access is accessed through the index; Object properties are accessed through the object name. Property name.
② after Json_encode () and data are JS can recognize the format, and after the Json_decode () of the data are the format of PHP can be recognized, this point we should be clear
③ after Json_encode () and output data are JSON-formatted JavaScript objects, in the foreground can be used as a JS object directly

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

PHP code online format Landscaping tools:
Http://tools.jb51.net/code/phpformat

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

JavaScript code Landscaping/compression/formatting/encryption Tools:
http://tools.jb51.net/code/jscompress

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

More about PHP Interested readers can view the site topics: "PHP JSON format data Operation tips Summary", "PHP file Operation Summary", "PHP operation and operator Usage Summary", "PHP Network Programming Skills Summary", "PHP basic Grammar Introductory Course", " PHP Operations Office Document Tips summary (including word,excel,access,ppt), "PHP Date and Time usage summary", "PHP Introduction to Object-oriented Programming", "PHP string (String) Usage Summary", "php+ MySQL Database operations Introduction tutorial and PHP Common database operation Skills Summary

I hope this article will help you with your PHP programming.

Related Article

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.