json_decode没有通过curl调用返回正确的api响应php数组

时间:2014-08-11 05:34:33

标签: php arrays curl json

我正在为我的一位客户提供送货API。我有来自供应商的运输api。在以json格式制作curl请求时,json响应没有转换为php数组?找到以下代码:

$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函数,以下是输出:

  

{“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,   “包裹”:[{“status”:“成功”,“运单”:“0008110000125”,   “refnum”:“8”,“client”:“demo”,“remarks”:“”,“cod_amount”:   21841.0,“付款”:“现金”},“cash_pickups”:21841.0} 1

     

1

我收到2输出为:1

我想在php中访问此响应的数组。我试过json_decode()但它没有正确响应。 需要你的输入。提前谢谢。

3 个答案:

答案 0 :(得分:4)

问题是您还没有设置CURLOPT_RETURNTRANSFER选项。在这种情况下,CURL直接将响应输出到STDOUT(浏览器),curl_exec返回true。由于此json_decode无法解码$result变量(因为它的值为true)。

所以你必须设置CURLOPT_RETURNTRANSFER选项:

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

答案 1 :(得分:1)

你忘了添加这个

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

答案 2 :(得分:0)

请在下面尝试一下

$results = json_decode(file_get_contents('php://input'), true);

而不是

$results = json_decode($result, true);