php api call json 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: create curl api request php with para

// create & initialize a curl session
$curl = curl_init();

// set our url with curl_setopt()
curl_setopt($curl, CURLOPT_URL, "api.example.com");

// return the transfer as a string, also with setopt()
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// curl_exec() executes the started curl session
// $output contains the output string
$output = curl_exec($curl);

// close curl resource to free up system resources
// (deletes the variable made by curl_init)
curl_close($curl);

Example 4: create curl api request php with para

$data_array =  array(
   "amount" => (string)($lease['amount'] / $tenant_count)
);
$update_plan = callAPI('PUT', 'https://api.example.com/put_url/'.$lease['plan_id'], json_encode($data_array));
$response = json_decode($update_plan, true);
$errors = $response['response']['errors'];
$data = $response['response']['data'][0];

Tags:

Php Example