contructing API with PHP JSON
I am dealing with API between websites, and it doesn't work well. :/ (I am php beginner)
Viaapi_login()
, I send$data
to fakeapiurl.com/Zone and get the zone data in$zone
.
function api_login () {
$data = [
'COM_CODE' => '1234',
'USER_ID' => 'user',
);
$ch = curl_init("https://fakeapiurl.com/Zone");
$payload = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result);
$zone = $json->Data->ZONE;
}
I don't know whether the line below is right. My intention is to group the zone data in the$data
array.
array_push($data, $zone);
My hope is to make$data
just like this:
$data = array(
'COM_CODE' => '1234',
'USER_ID' => 'user',
'ZONE' => $zone,
);
Only when the$data
is set, I can login and get the session id.
$ch = curl_init("https://fakeapiurl.com/Login");
$payload = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result);
$session_id = $json->Data->SESSION_ID;
return $session_id;
I've searched for php, json related pages, but couldn't find why my code doesn't work. Your help will be so much appreciated. Thanks!
Answer
Solution:
To do this try
Instead of
array_push($data, $zone);
. (Your solution wouldn't set the"ZONE"
key on$zone
).