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.
1 2 3 4 5 6 | <?php $arr = array('name' => 'Prem Tiwari', 'age' => 25, 'city' => 'Noida', 'country' => 'india'); echo json_encode($arr); ?> |
The above example will output:
1 | {"name":"Prem Tiwari","age":25,"city":"Noida","country":"india"} |
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) } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { "firstName": "Prem", "lastName": "Tiwari", "age": 25, "address": { "streetAddress": "965 3rd Floor", "city": "Noida", "state": "UP", "postalCode": 201301 }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "123 456-4567" } ] } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: how to use json with php, json, json and php tutorial, json example php, learn json, parse string in php, PHP, php and json example, php json database, php json example, php json example code, php json examples, valid json format, what is json in php with example