Json_decode does not return the php array of the api response correctly with a looped call

advertisements

I am working on the shipping API for one of my client. I have the shipping api from the vendor. On making curl request in json format, the json response is not converted into php array? Find the code below:

$params['format'] = 'json';
$params['data'] =json_encode($package_data);
$token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$url = "http://test.shipping.co/push/json/?token=".$token;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
$results = json_decode($result, true);
print_r($results);

Here I have 2 print_r function, and following is the output:

{ "cash_pickups_count": 1.0, "cod_count": 0, "success": true, "package_count": 1, "upload_wbn": "UPL21969440", "replacement_count": 0, "cod_amount": 0.0, "prepaid_count": 0, "pickups_count": 0, "packages": [ { "status": "Success", "waybill": "0008110000125", "refnum": "8", "client": "demo", "remarks": "", "cod_amount": 21841.0, "payment": "Cash" } ], "cash_pickups": 21841.0 }1

1

I am receiving 2 output as : 1

I want to access the array in php of this response. I tried json_decode() but it is not responding properly. Need your inputs here. Thanks in advance.


The problem is that you haven't set CURLOPT_RETURNTRANSFER option. In this case CURL outputs response directly into STDOUT (browser) and curl_exec returns true. Because of this json_decode cannot decode $result variable (since it has value = true).

So you have to set CURLOPT_RETURNTRANSFER option:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
$results = json_decode($result, true);
print_r($results);