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// 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]);
1<?php
2
3$data = '{
4 "name": "Aragorn",
5 "race": "Human"
6}';
7
8$character = json_decode($data);
9echo $character->name;
1<?php
2$jsonurl = "https://reqres.in/api/users/2";
3$json = file_get_contents($jsonurl);
4$jsonDecode = json_decode($json, true);
5echo $jsonDecode['data']['email'];
6?>
1//code igniter
2$query="qry";
3$query = $this->db->query($query);
4$res=$query->result();
5return json_encode($res);