contructing API with PHP JSON

796

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!

240

Answer

Solution:

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,
);

To do this try

$data['ZONE'] = $zone;

Instead ofarray_push($data, $zone);. (Your solution wouldn't set the"ZONE" key on$zone).

People are also looking for solutions to the problem: PHP string split after specified characters

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.