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
1$personJSON = '{"name":"Johny Carson","title":"CTO"}';
2
3$person = json_decode($personJSON);
4
5echo $person->name; // Johny Carson
1// function to return JSON response, you can set cors, also give status & data via arguments
2function json($status, $data) {
3 $cors = "*";
4 header("Access-Control-Allow-Origin: $cors");
5 header('Content-Type: application/json; charset=utf-8');
6 http_response_code($status);
7 echo json_encode($data);
8 }
9
10// example
11json(200, [
12 "status" => 200,
13 "message" => "action completed successfully",
14 "id" => 44236
15]);
1header('Content-Type: application/json');
2
3$colors = array("red","blue","green");
4echo json_encode($colors);
1$data = json_decode(file_get_contents('php://input'), true);
2print_r($data);
3echo $data;
4