Techniques for using JSON in the PHP language and implementation code for JSON _php instances

Source: Internet
Author: User
Currently, JSON has become one of the most popular formats for data interchange, with almost all the APIs of the major websites supporting it.

I wrote a "data type and JSON format" to explore its design ideas. Today, I want to summarize the PHP language support for it, which is what you must know to develop an Internet application, especially a writing API.

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

First, Json_encode ()

This function is primarily used 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": null}

Because JSON accepts only utf-8 encoded characters, the Json_encode () argument must be utf-8 encoded, otherwise it will get a null character or null. This is especially important when using GB2312 encoding in Chinese, or when using ISO-8859-1 encoding in a foreign language.

Second, indexed arrays and associative arrays

PHP supports two arrays, one is an indexed array (indexed array) that only holds "value", and the other is an associative array (associative array) that holds "name value pairs" (name/value).

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

For example, there is now an indexed array

$arr = Array (' One ', ' both ', ' three '); Echo Json_encode ($arr);

The result is:

["One", "one", "three"]

If you change it to an associative array:

$arr = Array (' 1 ' = ' one ', ' 2 ' = '-'-', ' 3 ' = ' three '); Echo Json_encode ($arr);

The result is changed:

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

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

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);

Iii. Conversion of classes (class)

The following is a PHP class:

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

Now, JSON transforms the instance of this class:

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

The output is

{"PUBLIC_EX": "This was public"}

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

Iv. Json_decode ()

This function is used to convert the 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 instead of 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 of 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"] = + int (4) ["e"] = I NT (5)}

V. Common errors in Json_decode ()

The following three kinds of JSON notation are wrong, can you see where is wrong?

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

Executing Json_decode () on these three strings will return null and error.

The first error is that the JSON delimiter (delimiter) only allows double quotation marks and cannot use single quotes. The second error is the "name" of the JSON name-value pair (the left part of the colon), which must use double quotes in any case. The third error is that you cannot add a comma after the last value (trailing comma).

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

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

Let us introduce the JSON implementation of PHP language

Due to the development of an AJAX File manager for Web open source project, data interchange using the JSON format, later found to run on the lower version of PHP will have problems, carefully debug found Json_decode and Json_encode does not work properly, So check the data, found that the lower version of PHP did not implement these two functions, for compatibility, I have to implement a PHP version of the JSON encoding decoding code, and to ensure that the same as json2.js, test debugging and pass, and now publish it, for the same needs of students to use:

<?php/* * **************************************************************************** * $base: $ * * $Author: $ * Berlin Qin * * $History: Base.js $ * Berlin Qin//created * * $contacted * webfmt@gmail.com * www.we bfmt.com * * *************************************************************************** */* ====================== ===================================================== * License * *, Open Source Licenses * webfmt is distributed unde  R the GPL, LGPL and MPL open source licenses.  * This triple copyleft licensing model avoids incompatibility with other open source licenses.  * These Open source licenses is 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, * and not a  ble or interested on supporting WEBFMT and its development. * *, Commercial license–fbis SourCE Closed Distribution LICENSE-CDL * For many companies and products, Open Source licenses is not a option.  * The Fbis source Closed distribution License (CDL) has been introduced. * It is a non-copyleft license which gives companies complete freedom * when integrating webfmt to their products and W  EB sites.  * This license offers a very flexible-to-integrate WEBFMT in your commercial application.  * These is the main advantages it offers over a Open Source license: * Modifications and enhancements doesn ' t need to  Be 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 hav  E to is done;  * No references to WEBFMT has to is done in any file distributed with your product;  * The source code of WEBFMT doesn ' t has been distributed alongside with your product;  * Can remove any file from webfmt when integrating it with your product. * The CDLis a lifetime license valid for all releases of WEBFMT published during * and before the year following its purchase. * 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 ', ': break;           Default:break; }}} $json = Str_replace (Array ("&#;", "&#;", "$"), Array ("\\\\", "\\\" "," \\$ "), Implode (" ",       $parts));     $result = eval ("return $json;");   }} catch (Exception $e) {$result = array ("error" = = $e->getcode ()); } return $result;     } 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 (Key ($arr))) {$result = "[";  for ($i =; $i < count ($arr), $i + +) {if (Is_array ($arr [$i])) {$result = $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 = "[]"; }}} catch (Exception $e) {} return $result;  }?>

If there is any problem with the use of the process, you can email me. Please point out the mistake!

  • 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.