json_de code未回,卷曲呼叫API响应的正确PHP数组 [英] json_decode is not returning proper php array of api response with curl call
问题描述
我的工作对航运API为我的客户之一。我从供应商船运API。在作出JSON格式卷曲请求,JSON响应不转化为PHP数组?在下面找到code:
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);
在这里,我有2个print_r的功能,下面是输出:
Here I have 2 print_r function, and following is the output:
{cash_pickups_count:1.0,cod_count:0,成功:真实,
package_count:1,upload_wbn:UPL21969440,replacement_count:
0,cod_amount:0.0,prepaid_count:0,pickups_count:0,
套餐:[{地位:成功,运单:0008110000125
引用句柄:8,客户:演示,备注:,cod_amount:
21841.0,支付:现金}],cash_pickups:21841.0} 1
{ "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
我收到2输出:1
我要访问数组中的这种反应PHP。我试图json_de code(),但它没有正确响应。
这里需要你的投入。先谢谢了。
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.
推荐答案
的问题是,你没有设置 CURLOPT_RETURNTRANSFER
选项。在这种情况下卷曲直接输出响应到 STDOUT
(浏览器)和 curl_exec
收益真实
。正因为如此 json_de code
不能去code $结果
变量(因为它的价值= 真正
)。
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
).
所以,你必须设置 CURLOPT_RETURNTRANSFER
选项:
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);
这篇关于json_de code未回,卷曲呼叫API响应的正确PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!