php get json code example

Example 1: 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 2: php response json

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

Example 3: php return json

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

Example 4: php return json data

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

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

Example 5: fetch value from json link in php

$ch = curl_init();
// IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);

$obj = json_decode($result);
echo $obj->access_token;

Example 6: how to get data from json array in php

$data = json_decode($json);