1<?php
2$data = ['name' => 'John', 'age' => 35];
3header('Content-type: Application/json');
4echo json_encode($data);
5
1$myArr = array("apple", "banana", "mango", "jackfruit");
2
3$toJSON = json_encode($myArr);
4
5echo $toJSON;
1<?php
2 // JSON string
3 $someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
4
5 // Convert JSON string to Array
6 $someArray = json_decode($someJSON, true);
7 print_r($someArray); // Dump all data of the Array
8 echo $someArray[0]["name"]; // Access Array data
9
10 // Convert JSON string to Object
11 $someObject = json_decode($someJSON);
12 print_r($someObject); // Dump all data of the Object
13 echo $someObject[0]->name; // Access Object data
14?>
15
1//Json Encode
2
3$person = array(
4 "name" => "KINGASV",
5 "title" => "CTO"
6);
7$personJSON=json_encode($person);//returns JSON string
8
9//Json Decode
10
11$personJSON = '{"name":"KINGASV","title":"CTO"}';
12
13$person = json_decode($personJSON);
14
15echo $person->name; // KINGASV
16
1function IsJsonString(str) {
2 try {
3 JSON.parse(str);
4 } catch (e) {
5 return false;
6 }
7 return true;
8}
1function getJsonData(){
2 $var = get_object_vars($this);
3 foreach ($var as &$value) {
4 if (is_object($value) && method_exists($value,'getJsonData')) {
5 $value = $value->getJsonData();
6 }
7 }
8 return $var;
9}
10