php json response code example

Example 1: php change header to json

<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

Example 2: php convert array to json object

$myArr = array("apple", "banana", "mango", "jackfruit");

$toJSON = json_encode($myArr);

echo $toJSON;

Example 3: json php

//Json Encode

$person = array( 
    "name" => "KINGASV", 
    "title" => "CTO"
); 
$personJSON=json_encode($person);//returns JSON string

//Json Decode

$personJSON = '{"name":"KINGASV","title":"CTO"}';

$person = json_decode($personJSON);

echo $person->name; // KINGASV

Example 4: php return json

header('Content-type: application/json');
echo json_encode($array);

Example 5: php json encode

$person = array( 
    "name" => "Johny Carson", 
    "title" => "CTO"
); 
$personJSON=json_encode($person);//returns JSON string

Example 6: php return json data

header('Content-Type: application/json'); 

$colors = array("red","blue","green");
echo json_encode($colors);