The technique of using JSON in PHP language and the implementation code of JSON _php instance

Source: Internet
Author: User
Tags php language numeric value sprintf

At present, JSON has become one of the most popular data interchange formats, and almost all the APIs in the major Web sites support it.

I've written a data type and JSON format to explore its design ideas. Today, I want to summarize the PHP language's support for it, which is the knowledge you must know to develop an Internet application, especially to write an API.

Starting with version 5.2, PHP native provides Json_encode () and Json_decode () functions, which are used for encoding and decoding.

One, Json_encode ()

This function is used primarily to convert arrays and objects into JSON format. Let's look at an example of an array conversion:

$arr = Array (' A ' =>1, ' B ' =>2, ' C ' =>3, ' d ' =>4, ' e ' =>5);
echo Json_encode ($arr);

Result is

{"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}

Let's look at an example of an object conversion:

$obj->body      = ' another post ';
$obj->id       =;
$obj->approved    = true;
$obj->favorite_count = 1;
$obj->status     = NULL;
echo Json_encode ($obj);

Result is

{
"body": "Another post",
"id": "
Approved": True,
"Favorite_count": 1,
"status": N Ull
}

Since JSON only accepts UTF-8 encoded characters, the Json_encode () argument must be utf-8 encoded, or it will get null characters or NULL. Special attention should be paid to the use of GB2312 encoding in Chinese, or the use of iso-8859-1 encoding in foreign languages.

index arrays and associative arrays

PHP supports two types of arrays, one is the index array (indexed array) that holds only the value, the other is an associative array (associative array) that holds the name value pair (name/value).

Because JavaScript does not support associative arrays, json_encode () only converts an indexed array (indexed array) into an array format and an associative array (associative array) into object format.

For example, now there is an array of indices

$arr = Array (' One ', ' two ', ' three ');
echo Json_encode ($arr);

The results are:

["One", "two", "three"]

If you change it to an associative array:

$arr = Array (' 1 ' => ' one ', ' 2 ' => ' two ', ' 3 ' => ' three ');
echo Json_encode ($arr);

The result is changed:

{"1": "One", "2": "Two", "3": "Three"}

Note that the data format becomes "{}" (object) from "[]" (array).

If you need to force an "indexed array" into an "object", you can write

Json_encode ((object) $arr);

Or

Json_encode ($arr, json_force_object);

Classes (Class) conversion

The following is a class of PHP:

Class Foo {
const   error_code = ' 404 ';
Public  $public _ex = ' it is public ';
Private  $private _ex = ' this is private! ';
protected $protected _EX = ' This should to be protected ';
Public Function GetErrorCode () {return
self::error_code;
}
}

Now, make a JSON conversion to an instance of this class:

$foo = new Foo;
$foo _json = Json_encode ($foo);
echo $foo _json;

The output result is

{' PUBLIC_EX ': ' This is public '}

As you can see, other things (constants, private variables, methods, and so on) are lost in addition to exposing variables (public).

Iv. Json_decode ()

This function is used to convert JSON text to the appropriate PHP data structure. Here is an example:

$json = ' {' foo ': 12345} ';
$obj = Json_decode ($json);
Print $obj->{' foo '}; 12345

Typically, Json_decode () always returns a PHP object, not an array. Like what:

$json = ' {' A ': 1, "B": 2, "C": 3, "D": 4, "E": 5} ';
Var_dump (Json_decode ($json));

The result is to generate a PHP object:

Object (StdClass) #1 (5) {
["a"] => int (1)
["B"] => int (2)
["C"] => int (3)
["D"] => int (4)
["E"] => int (5)
}    

If you want to force a PHP associative array to be generated, json_decode () needs to add a parameter true:

$json = ' {' A ': 1, "B": 2, "C": 3, "D": 4, "E": 5} ';
Var_dump (Json_decode ($json, true));

As a result, an associative array is generated:

Array (5) {
["a"] => int (1)
["B"] => int (2)
["C"] => int (3)
["D"] => I NT (4)
["E"] => int (5)
}    

V. Common errors in Json_decode ()

The following three kinds of JSON are all wrong, can you see what's wrong?

$bad _json = "{' Bar ': ' Baz '}";
$bad _json = ' {bar: ' Baz '} ';
$bad _json = ' {' bar ': ' Baz ',} ';

Performing Json_decode () on these three strings will return null and have an error.

The first error is that the JSON delimiter (delimiter) only allows double quotes and cannot use single quotes. The second error is the name of the JSON name value pair (the part to the left of the colon), which must be used in double quotes in any case. The third error is that a comma (trailing comma) cannot be added after the last value.

In addition, JSON can only be used to represent objects (object) and Arrays (array), and null will be returned if Json_decode () is used for a string or numeric value.

Var_dump (Json_decode ("Hello World")); Null

Let me introduce you to the JSON implementation of PHP language

As a result of developing an Ajax File Manager for Web open source project, the JSON format used for data interchange, later found that running on a lower version of PHP would be problematic, and careful debugging found that Json_decode and Json_encode were not working properly, so consult the data, found that the lower version of PHP does not implement these two functions, in order to compatibility, I have to implement a PHP version of the JSON coding and decoding code, and to ensure consistency with the json2.js, test debugging and through, now publish it out for the same needs of students to use:

<?php/* **************************************************************************** * $base: $ * * $Author:  
 $ * Berlin Qin * * $History: Base.js $ * Berlin Qin//created * * $contacted * webfmt@gmail.com * www.webfmt.com * * *************************************************************************** * * =========  ================================================================== * License *, Open Source Licenses * WEBFMT is 
 Distributed under the GPL, LGPL and MPL open source licenses. 
 * This triple copyleft the licensing model avoids incompatibility with the other open source licenses. 
 * These are open source licenses are specially indicated for: * Integrating WEBFMT into Open source software; 
 * Personal and educational use of webfmt;  * Integrating WEBFMT in commercial software, * Taking care of satisfying the Open Source licenses terms 
 Able or interested on supporting WEBFMT and its development. * *, COmmercial license–fbis Source Closed Distribution LICENSE-CDL * For many companies and products, Open source License 
 s are not a option. 
 * This is why the Fbis source Closed distribution License (CDL) has been. * It is a non-copyleft license which gives companies complete to freedom integrating 
 Web sites. 
 * This license offers a very flexible way to integrate WEBFMT in your commercial. * These are the main advantages it offers over an Open Source license: * Modifications and enhancements doesn ' t need t 
 O is released under an Open Source license; * There is no need to distribute any Open Source license terms alongside with your product * and no reference to it ha 
 ve to being done; 
 * No references to webfmt have to being done in any file distributed with your product; 
 * The source code of WEBFMT doesn ' t have to is distributed alongside with your product; * You can remove any file from Webfmt when inteGrating it with your product. * The CDL is a lifetime license valid to all releases of WEBFMT published during * and before the year following its PU 
 Rchase. * It ' s valid for WEBFMT releases also. 
 It includes year of personal e-mail support. * 
 * ************************************************************************************************************* 
  */function Jsondecode ($json) {$result = array (); 
    try {if (php_version_id >) {$result = (array) json_decode ($json); 
      else {$json = Str_replace (Array ("\\\\", "\\\"), Array ("&#;", "&#;"), $json); $parts = Preg_split ("@" [^\ "]*\") | ( [\[\]\{\},:])| \s@is ", $json,-, Preg_split_no_empty | 
      Preg_split_delim_capture); 
          foreach ($parts as $index => $part) {if (strlen ($part) = =) {switch ($part) {case ' [': Case ' {': $parts [$index] = "Array ("; 
            Break 
              Case "]": Case "}": $parts [$index] = ")"; 
            Break 
              Case ":": $parts [$index] = "=>"; 
            Break 
            Case ",": the break; 
          Default:break; }} $json = Str_replace (Array ("&#;", "&#;", "$"), Array ("\\\\", "\\\", "\\$"), Implode (" 
      ", $parts)); 
    $result = eval ("return $json;"); 
  The catch (Exception $e) {$result = array ("error" => $e->getcode ()); 
return $result; 
    The function valuetostr ($val) {if (is_string ($val)) {$val = Str_replace (' \ "," \\\ ", $val); 
    $val = Str_replace ("\", "\\\\", $val); 
    $val = Str_replace ("/", "\\/", $val); 
    $val = Str_replace ("T", "\\t", $val); 
    $val = Str_replace ("\ n", "\\n", $val); 
    $val = Str_replace ("\ r", "\ R", $val); 
    $val = str_replace ("\b", "\\b", $val); $vaL = str_replace ("\f", "\\f", $val); Return ' "'. $val. 
  '"'; 
  ElseIf (Is_int ($val)) return sprintf ('%d ', $val); 
  ElseIf (Is_float ($val)) return sprintf ('%F ', $val); ElseIf (Is_bool ($val)) return ($val? 
  ' True ': ' false '); 
else return ' null '; 
  function Jsonencode ($arr) {$result = ' {} '; 
    try {if (php_version_id >) {$result = Json_encode ($arr); 
      else {$parts = array (); 
      $is _list = false; 
      if (!is_array ($arr)) {$arr = (array) $arr; 
      $end = count ($arr)-;  
          if (count ($arr) >) {if (Is_numeric ($arr)) {$result = "[); for ($i =; $i < count ($arr); $i + +) {if (Is_array ($arr [$i])) {$re Sult = $result. 
            Jsonencode ($arr [$i]); 
         else {$result = $result. Valuetostr ($arr [$i]);   } if ($i!= $end) {$result = $result. 
            ","; }} $result = $result. 
        "]";  
          else {$result = ' {'; 
          $i =; foreach ($arr as $key => $value) {$result = $result. '"' . $key. 
            '":'; 
            if (Is_array ($value)) {$result = $result. Jsonencode ($value); 
            else {$result = $result. Valuetostr ($value); } if ($i!= $end) {$result = $result. 
            ","; 
          } $i + +; } $result = $result. 
        "}"; 
      } else {$result = ' [] '; 
The catch (Exception $e) {} return $result;  }?>

If you have any problems with the process, you can email me. Welcome to point out mistakes!

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.