JSON (json_encode) encoded in PHP)
The PHP json_encode () function is used for JSON encoding in PHP. This function returns the value in JSON format. If it fails, FALSE is returned.
Syntax:
String json_encode ($ value [, $ options = 0]) parameter:
Value: the value to be encoded. This function applies only to data encoded by the UTF-8.
Options: This optional value is a bitmask consisting of JSON_HEX_TAG JSON_HEX_QUOT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, response, JSON_FORCE_OBJECT
Example
The following example demonstrates how to convert a PHP array to JSON:
| The Code is as follows: |
|
|
<? Php
$ Arr = array ('A' => 1, 'B' => 2, 'c' => 3, 'D' => 4, 'E' => 5 );
Echo json_encode ($ arr );
?>
During execution, the following results are generated:
{"A": 1, "B": 2, "c": 3, "d": 4, "e": 5} |
The following example shows how to convert a PHP Object To JSON:
| The Code is as follows: |
|
|
<? Php
Class Emp {
Public $ name = "";
Public $ hobbies = "";
Public $ birthdate = "";
}
$ E = new Emp ();
$ E-> name = "running in ";
$ E-> hobbies = "sports ";
$ E-> birthdate = date ('m/d/Y h: I: s A', "8/5/1974 12:20:03 p ");
$ E-> birthdate = date ('m/d/Y h: I: s A', strtotime ("8/5/1974 12:20:03 "));
Echo json_encode ($ e );
?>
During execution, the following results are generated:
{"Name": "coming in", "hobbies": "sports", "birthdate": "08/05/1974 12:20:03 "} |
Decoding JSON in PHP (json_decode)
PHP json_decode () function is used to decode JSON in PHP. The return value of this function is decoded from json to the appropriate PHP type.
Syntax:
Mixed json_decode ($ json [, $ assoc = false [, $ depth = 512 [, $ options = 0]) parameter:
Json_string: it must be a UTF-8-encoded data-encoded string
Assoc: when this is a Boolean parameter set to TRUE, the returned object will be converted to an associated array.
Depth: it is an integer parameter that specifies the recursive depth
Options: JSON Decoding of A bitmask of the integer type. JSON_BIGINT_AS_STRING is supported.
Example
The following example shows how to use PHP to decode JSON objects:
| The Code is as follows: |
|
|
<? Php
$ Json = '{"a": 1, "B": 2, "c": 3, "d": 4, "e": 5 }';
Var_dump (json_decode ($ json ));
Var_dump (json_decode ($ json, true ));
?>
During execution, the following results are generated:
Object (stdClass) #1 (5 ){
["A"] => int (1)
["B"] => int (2)
["C"] => int (3)
["D"] => int (4)
["E"] => int (5)
}
Array (5 ){
["A"] => int (1)
["B"] => int (2)
["C"] => int (3)
["D"] => int (4)
["E"] => int (5)
} |
Assume that the JSON data we obtain is as follows: (you can use curl, fsockopen, and so on)
| The Code is as follows: |
|
|
{
"Translation": ["Hello world"],
"Query": "Hello world ",
"ErrorCode": 0,
"Web ":[
{
"Value": ["hello world"],
"Key": "Hello World"
},
{
"Value": ["Hello World"],
"Key": "Hello World"
}
]
}
Use the json_decode function to return the array:
Array
(
[Translation] => Array
(
[0] => Hello world
)
[Query] => Hello World
[ErrorCode] => 0
[Web] => Array
(
[0] => Array
(
[Value] => Array
(
[0] => hello world
)
[Key] => Hello World
)
[1] => Array
(
[Value] => Array
(
[0] => Hello World
)
[Key] => Hello World
)
)
) |
We can use the following methods in PHP to obtain the desired value:
| The Code is as follows: |
|
|
<? Php
/*----------------------------------
$ Data ='
{
"Translation": ["Hello world"],
"Query": "Hello world ",
"ErrorCode": 0,
"Web ":[
{
"Value": ["hello world"],
"Key": "Hello World"
},
{
"Value": ["Hello World"],
"Key": "Hello World"
}
]
}
';
-------------------------------------*/
$ Data = <STR
{
"Translation": ["Hello world"],
"Query": "Hello world ",
"ErrorCode": 0,
"Web ":[
{
"Value": ["hello world"],
"Key": "Hello World"
},
{
"Value": ["Hello World"],
"Key": "Hello World"
}
]
}
STR;
$ Jsondata = json_decode ($ data, true );
Header ("Content-Type: text/html; charset = UTF-8 ");
// Print_r ($ jsondata );
Echo "<br/>". $ jsondata ['translation'] [0]; // Hello world
Echo "<br/>". $ jsondata ['query']; // Hello World
Echo "<br/>". $ jsondata ['web'] [0] ['value'] [0]; // hello world
Echo "<br/>". $ jsondata ['web'] [1] ['key']; // Hello, world
?> |
Example, combined with database operations
| The Code is as follows: |
|
|
<? Php
Include './include/conn. php'; // database link file
$ SQL _notice = mysql_query ('select * FROM gg_notice where enable = "1" limit 0, 10 ');
$ Notice = mysql_fetch_array ($ SQL _notice, MYSQL_ASSOC );
Print_r ($ notice );
?>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> tutorial provided by the first php Network -- generate json format for data read from the database </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<! -- <Script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type = "text/javascript"/> </script> -->
<Script language = javascript>
</Script>
</Head>
<Body>
<Pre>
<H1> pay attention to the difference in structure between the object arrays generated by the two methods
<? Php
Echo '// Assume that the following array is generated based on the data we read from the database.
$ Jarr = array ('Total' => 239, 'row' => array (
Array ('code' => '001', 'name' => 'www.111cn.net ', 'add' => 'address 11 ', 'col4' => 'col4 data '),
Array ('code' => '002 ', 'name' => 'name 2', 'addr' => 'address 12 ', 'col4' => 'col4 data '),
)
);
// Method 1:
$ Jobj = new stdclass (); // instantiate stdclass, which is an empty class built in php and can be used to transmit data. Because the data after json_decode is stored as an object array,
// Therefore, we need to store the data in the object during generation.
Foreach ($ jarr as $ key => $ value ){
$ Jobj-> $ key = $ value;
}
Print_r ($ jobj); // print the object after passing the attribute
Echo 'use $ jobj-> row [0] ['code'] to output array elements :'. $ jobj-> row [0] ['code']. '<br> ';
Echo 'encoded json string: '. json_encode ($ jobj).' <br> '; // print the encoded json string
Echo '// Method 2:
Echo 'Echo 'encoded json string :';
Echo $ str = json_encode ($ jarr); // encode the array in json format.
Echo '<br> ';
$ Arr = json_decode ($ str); // perform json decoding.
Print_r ($ arr); // print the decoded array. The data is stored in the object array.
Echo 'use $ arr-> row [0]-> code output array element:'. $ arr-> row [0]-> code;
?>
</Body>
</Html> |