Home > Backend Development > PHP Tutorial > PHP uses JSON example analysis_PHP tutorial

PHP uses JSON example analysis_PHP tutorial

WBOY
Release: 2016-07-13 10:38:56
Original
940 people have browsed it

Encoding JSON in PHP (json_encode)

 PHP json_encode() function is used to encode JSON in PHP. This function returns the value represented by JSON on success, or FALSE on failure.

Grammar:

 string json_encode ( $value [, $options = 0 ] ) parameters:

Value: The value to be encoded. This function only applies to UTF-8 encoded data.

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, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT

Example

The following example demonstrates how to convert an array to JSON using PHP:

The code is as follows

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

 代码如下  

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
   echo json_encode($arr);
?>

在执行过程中,这将产生以下结果:

{"a":1,"b":2,"c":3,"d":4,"e":5}

When executed, this will produce the following results :

{"a":1,"b" :2,"c":3,"d":4,"e":5}

 代码如下  

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

在执行过程中,这将产生以下结果:

{"name":"sachin","hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"}

The following example shows how a PHP object can be converted into JSON:
The code is as follows

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

When executed, this will produce the following results :

{"name":"sachin"," hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"}

Decoding JSON in PHP (json_decode)

 PHP json_decode() function is used to decode JSON in PHP. This function returns the value decoded from json into the appropriate PHP type.

Grammar:

Mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]]) Parameters:

json_string: It must be a UTF-8 encoded data-encoded string

 assoc: This is a boolean type parameter. When set to TRUE, the returned object will be converted into an associative array

Depth: It is an integer type parameter that specifies the recursion depth

Options: It is a bit mask JSON decoding of integer type, supporting JSON_BIGINT_AS_STRING

Example

The following example shows how you can use PHP to decode a JSON object:

The code is as follows

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

代码如下

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>

在执行过程中,这将产生以下结果:

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

var_dump(json_decode($json)); var_dump(json_decode($json, true));
?>

When executed, this will produce 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)
}

Suppose the JSON data we obtain is as follows: (can be obtained using curl, fsockopen, etc.)

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"
}
]
}

 代码如下  

{
 "translation":["Hello world"],
 "query":"你好世界",
 "errorCode":0,
 "web":[
  {
   "value":["hello world"],
   "key":"你好世界"
  },
  {
   "value":["Hello World"],
   "key":"世界你好"
  }
 ]
}

用json_decode函数返回array的方式得到:

Array
(
 [translation] => Array
  (
   [0] => Hello world
  )
 [query] => 你好世界
 [errorCode] => 0
 [web] => Array
  (
   [0] => Array
    (
     [value] => Array
      (
       [0] => hello world
      )
     [key] => 你好世界
    )
   [1] => Array
    (
     [value] => Array
      (
       [0] => Hello World
      )
     [key] => 世界你好
    )
  )
)

Use the json_decode function to return array to get:

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 method to get the value we want in PHP language:

The code is as follows

/*----------------------------------
$data = '
{
"translation":["Hello world"],
"query":"Hello world",
"errorCode":0,
"web":[
{
"value":["hello world"],
"key":"Hello World"
},
{
"value":["Hello World"],
"key":"Hello world"
}
]
}
';
---------------------------------------------*/
$data = << {
"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 "
".$jsondata['translation'][0]; //Hello world
echo "
".$jsondata['query']; //Hello world
echo "
".$jsondata['web'][0]['value'][0]; //hello world
echo "
".$jsondata['web'][1]['key']; //Hello world
?>

 代码如下  

/*----------------------------------
$data = '
{
"translation":["Hello world"],
"query":"你好世界",
"errorCode":0,
"web":[
{
"value":["hello world"],
"key":"你好世界"
},
{
"value":["Hello World"],
"key":"世界你好"
}
]
}
';
-------------------------------------*/
$data = << {
"translation":["Hello world"],
"query":"你好世界",
"errorCode":0,
"web":[
{
"value":["hello world"],
"key":"你好世界"
},
{
"value":["Hello World"],
"key":"世界你好"
}
]
}
STR;
$jsondata=json_decode($data,true);
header("Content-Type: text/html; charset=UTF-8");
//print_r($jsondata);
echo "
".$jsondata['translation'][0]; //Hello world
echo "
".$jsondata['query']; //你好世界
echo "
".$jsondata['web'][0]['value'][0]; //hello world
echo "
".$jsondata['web'][1]['key']; //世界你好
?>

Example, combined with database operation

The code is as follows

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



Tutorial provided by the first php website - Generate json format from data read from the database






Please note the structural difference between the object arrays generated by the two methods


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'=>'China www.111cn.net','addr'=>'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 into PHP and can be used to transfer data. Since the data after json_decode is stored in the form of an object array,
//So when we generate it, we also need to store the data in the object
foreach($jarr as $key=>$value){
$jobj->$key=$value;
}
print_r($jobj);//Print the object after passing the attributes
echo 'Use $jobj->row[0]['code'] to output array elements:'.$jobj->row[0]['code'].'
';
echo 'Encoded json string:'.json_encode($jobj).'
';//Print the encoded json string


echo '


';
//Method 2:
echo '

Method 2

';
echo 'Encoded json string:';
echo $str=json_encode($jarr);//Encode the array into json
echo '
';
$arr=json_decode($str);//Decode json again
print_r($arr);//Print the decoded array, the data is stored in the object array
echo 'Use $arr->row[0]->code to output array elements:'.$arr->row[0]->code;

?>


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/733189.htmlTechArticleEncoding JSON in PHP (json_encode) The PHP json_encode() function is used to encode JSON in PHP. This function returns the value represented by JSON on success, or FALSE on failure. Syntax: string json_encode ( $va...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template