Laurie Williams Laurie Williams -4 years ago 143
JSON Question

Return php variable from CURL post

I working with the TradeGecko API and need to create a new customer via a curl post request. It creates the post successfully and returns a json response (below). How do I retrieve the

from the JSON response as a PHP variable?

function createCompany($client, $customerID, $customer_first_name, $customer_last_name, $customer_company_name,
$customer_company_email, $customer_company_phone)

//API Url
$url = '';

//Initiate cURL.
$ch = curl_init($url);

$jsonData =
'assignee_id' => NULL,
'default_ledger_account_id' => null,
'default_payment_term_id' => null,
'default_stock_location_id' => null,
'default_tax_type_id' => null,
'default_ledger_account_id' => null,
'default_payment_term_id' => null,
'default_stock_location_id' => null,
'default_tax_type_id' => null,
'company_code' => $customerID,
'company_type' => "consumer",
'default_discount_rate' => null,
'default_price_list_id' => null,
'default_tax_rate' => null,
'default_document_theme_id' => null,
'description' => "$customer_first_name $customer_last_name - synced for OceanAngler e-shop",
'email' => "$customer_company_email",
'fax' => null,
'name' => "$customer_first_name $customer_last_name",
'phone_number' => "$customer_company_phone",
'status' => 'active',
'tax_number' => null,
'website' => null, // double check this in orders
'default_price_type_id' => null


//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

$authorization = "Authorization: Bearer [token goes here]";

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));

//Execute the request
$result = curl_exec($ch);


It returns an output like this.

"description":"Aniken Skywalker - synced from e-shop",
"name":"Aniken Skywalker",




How do I return 'id' as a PHP variable?

Answer Source

The problem is with curl request, please add below code for value in $result.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

after that :

$data = json_decode($result);

$id =  $data->company->id;

echo $id;

Let me know in case any problem .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download