PHP using JSON instance analysis

Source: Internet
Author: User
Tags php language json php json print object

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

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


?&gt;


&lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt;


&lt;html xmlns= "http://www.w3.org/1999/xhtml" &gt;


&lt;head&gt;

Tutorials from
&lt;title&gt; first PHP web--Generate JSON format for data read from database &lt;/title&gt;


&lt;meta http-equiv= "Content-type" content= "text/html"; Charset=utf-8 "/&gt;


&lt;!--&lt;script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type= "Text/javascript" &gt;&lt;/script&gt;--&gt;


&lt;script language=javascript&gt;


&lt;/script&gt;


&lt;/head&gt;


&lt;body&gt;


&lt;pre&gt;


&lt;h1&gt; Note the structural differences in the array of objects generated by the two methods &lt;/h1&gt;


&lt;?php


Echo ' &lt;h1&gt; law i &lt;/h1&gt; ';


//Assume that the following arrays are generated from data that we read from the database


$jarr =array (' Total ' =&gt;239, ' Row ' =&gt;array (


Array (' Code ' =&gt; ' 001 ', ' name ' =&gt; ' China www.111cn.net ', ' addr ' =&gt; ' address one, ' col4 ' =&gt; ' col4 ' data '),


Array (' Code ' =&gt; ' 002 ', ' name ' =&gt; ' Name 2 ', ' addr ' =&gt; ', ' address ', ' col4 ' =&gt; ' 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 =&gt; $value) {


$jobj-&gt; $key = $value;


}


Print_r ($jobj);//Print object after passing property


Echo ' uses $jobj-&gt;row[0][' code ' to output an array element: '. $jobj-&gt;row[0][' code '. ' &lt;br&gt; ';


echo ' encoded JSON string: '. Json_encode ($jobj). ' &lt;br&gt;//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>

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.