Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP JSON

PHP JSON

This section will introduce how to use the PHP language to encode and decode JSON objects.


Environment Configuration

The JSON extension is built in from PHP 5.2.0 and above.


JSON Functions

function Description
json_encode Perform JSON encoding on a variable
json_decode Decode a JSON-formatted string into a PHP variable
json_last_error Return the last occurred error

json_encode

PHP json_encode() is used to perform JSON encoding on a variable. If executed successfully, it returns JSON data; otherwise it returns FALSE.

Syntax

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

Parameters

Example

The following example demonstrates how to convert a PHP array into JSON format data:



 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

   echo json_encode($arr);

?>

The execution result of the code above is:



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

The following example demonstrates how to convert a PHP object into JSON format data:

Example

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

The execution result of the code above is:



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

Using the JSON_UNESCAPED_UNICODE option

<

?php

   

$arr

= array

(

'runoob'

=

'Runoob Tutorial'

,

'taobao'

=

'Taobao'

)

;

   

echo

json_encode

(

$arr

)

;

//

Encode Chinese

   

echo

PHP_EOL;  

//

Newline

   

echo

json_encode

(

$arr

, JSON_UNESCAPED_UNICODE

)

;  

//

Do not encode Chinese

?

The execution result of the code above is:



{"runoob":"\u83dc\u9e1f\u6559\u7a0b","taobao":"\u6dd8\u5b9d\u7f51"}

{"runoob":"Runoob Tutorial","taobao":"淘宝网"}


json_decode

The PHP json_decode() function is used to decode a JSON-formatted string and convert it into a PHP variable.

Syntax



mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Parameters

Example

The following example demonstrates how to decode JSON data:

Example

The execution result of the code above is:



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)

}