How to use json in php

JSON ( JavaScript Object Notation ), is an open standard format that uses human-readable text to transmit data objects. The JSON standard only supports when you are using inside an array or an object in your web applications. There are the native functions in php language to encode and decode your JSON data. You can encode your data in JSON format using the ” json_encode() ” function and decode your data using json_decode() function.

Example (A) json_encode() example

1

2

3

4

5

6

<?php

$arr=array('name'=>'Prem Tiwari','age'=>25,'city'=>

'Noida','country'=>'india');

echojson_encode($arr);

?>

The above example will output:

1

{"name":"Prem Tiwari","age":25,"city":"Noida","country":"india"}

Example (B) json_decode() examples

1

2

3

4

5

6

7

<?php

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

var_dump(json_decode($json));

var_dump(json_decode($json,true));

?>

The above example will output:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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)

}

Data types, syntax and example

The following example shows the JSON representation. The object has string fields for first name and last name, age, an object representing the person’s address and phone number objects.