Encoding json in PHP (Json_encode)
The PHP Json_encode () function is used in PHP JSON encoding. This function returns the value represented by the JSON successfully and returns false if it fails.
Grammar:
String Json_encode ($value [, $options = 0]) parameter:
Value: The number to encode, which applies only to UTF-8 encoded data.
Options: This optional value is a bit mask, by Json_hex_tag Json_hex_quot,json_hex_amp,json_hex_apos,json_numeric_check,json_pretty_ Print,json_unescaped_slashes,json_force_object
Example
The following example shows how to convert a PHP array into 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, this produces the following results: {"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 = "Sachin"; $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, this produces the following results: {"Name": "Sachin", "hobbies": "Sports", "Birthdate": "08/05/1974 12:20:03 PM"} |
Decoding JSON in PHP (Json_decode)
The PHP Json_decode () function is used to decode json in PHP. This function returns the value from JSON and decodes it into the appropriate PHP type.
Grammar:
Mixed Json_decode ($json [, $assoc = False [, $depth = [, $options = 0]]] parameter:
Json_string: It must be a UTF-8 encoded string of data encoded
Assoc: This is when a Boolean type parameter is set to True, the returned object is converted to an associative array
Depth: It is an integer type parameter that specifies the recursive depth
Options: It is an integer type of bit mask JSON decoder that supports json_bigint_as_string
Example
The following example shows how you can use PHP to decode a JSON object:
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, this produces the following results: 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) } |
If we get the JSON data as follows: (can be obtained using curl, fsockopen, etc.)
code is as follows |
&nbs P; |
{ "translation": ["Hello World"], "query": "Hello Worlds ", " ErrorCode ": 0, " web ": [ { " value ": [" Hello World "], "key": "Hello World" }, { "value": ["Hello Worlds"], "key": "Hello World" ] Returns an array with the Json_decode function: Array ( [translation] => Array ( [0] => Hello World & nbsp; ) [query] => Hello World [errorcode] => 0 [web] => Array ( [0] => Array ( [value] => Array ( &Nbsp; [0] => Hello World ) [key] => Hello World ) [1] => Array ( [value] => Array ( [0] => Hello World ) [key] => World Hello ) ) |
We can get the values we want in the PHP language in the following ways:
code is as follows |
&nbs P; |
<?php /*---------------------------------- $data = ' { "translation": ["Hello World"], "query": "Hello Worlds", "ErrorCode": 0, "web": [ { "value": ["Hello World"], "key": "Hello Worlds" }, { "value": ["Hello World"], "key": "Hello Worldwide" &NBSP} ] '; -------------------------------------*/ $data = <<<str { "translation": ["Hello World"], "query": "Hello Worlds", "ErrorCode": 0, "web": [ { "value": ["Hello World"], "key": "Hello Worlds" }, { "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 ']; br> echo "<br/>". $jsondata [' web '][0][' value '][0]; Hello World echo "<br/>". $jsondata [' web '][1][' key '];//Hello! |
example, combined with database operation
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>
Tutorials from <title> first PHP web--Generate JSON format for data read from 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> Note the structural differences in the array of objects generated by the two methods </h1>
<?php
Echo ' <h1> law i </h1> ';
//Assume that the following arrays are generated from data that we read from the database
$jarr =array (' Total ' =>239, ' Row ' =>array (
Array (' Code ' => ' 001 ', ' name ' => ' China www.111cn.net ', ' addr ' => ' address one, ' col4 ' => ' col4 ' data '),
Array (' Code ' => ' 002 ', ' name ' => ' Name 2 ', ' addr ' => ', ' address ', ' col4 ' => ' col4 ' data '),
)
);
//Fayi:
$jobj =new Stdclass ()//instantiate Stdclass, which is a built-in null class in PHP that can be used to pass data, since Json_decode data is stored as an array of objects,
//So when we build, we also store the data in the object
foreach ($jarr as $key => $value) {
$jobj-> $key = $value;
}
Print_r ($jobj);//Print object after passing property
Echo ' uses $jobj->row[0][' code ' to output an array element: '. $jobj->row[0][' code '. ' <br> ';
echo ' encoded JSON string: '. Json_encode ($jobj). ' <br>//Print encoded JSON string Echo ' Law II: Echo ' Echo ' encoded JSON string: '; echo $str =json_encode ($jarr);//JSON encoding the array Echo ' <br> '; $arr =json_decode ($STR);//JSON decoding Print_r ($arr);//print decoded array, data stored in an object array Echo ' uses $arr->row[0]->code to output array elements: '. $arr->row[0]->code; ?> </body>
|