JSON没有解码,尽管是有效的PHP

时间:2017-10-06 21:25:18

标签: php json curl

我有一个json对象返回但是当我尝试解码时它会返回以下内容:

{"droplet":{"id":65243848,"name":"blah.com","memory":2048,"vcpus":2,"disk":40,"locked":true,"status":"new","kernel":null,"created_at":"2017-10-06T21:17:30Z","features":[],"backup_ids":[],"next_backup_window":null,"snapshot_ids":[],"image":{"id":28287672,"name":"NGINX-Stack-Blank-10/3/2017","distribution":"Ubuntu","slug":null,"public":false,"regions":["nyc1"],"created_at":"2017-10-03T22:17:46Z","min_disk_size":40,"type":"snapshot","size_gigabytes":2.03},"volume_ids":[],"size":{"slug":"2gb","memory":2048,"vcpus":2,"disk":40,"transfer":3.0,"price_monthly":20.0,"price_hourly":0.02976,"regions":["ams2","ams3","blr1","fra1","lon1","nyc1","nyc2","nyc3","sfo1","sfo2","sgp1","tor1"],"available":true},"size_slug":"2gb","networks":{"v4":[],"v6":[]},"region":{"name":"New York 1","slug":"nyc1","sizes":["512mb","1gb","2gb","c-2","4gb","c-4","8gb","c-8","16gb","m-16gb","c-16","32gb","m-32gb","48gb","c-32","m-64gb","64gb","m-128gb","m-224gb"],"features":["private_networking","backups","ipv6","metadata","install_agent","storage"],"available":true},"tags":[]},"links":{"actions":[{"id":301502253,"rel":"create","href":"https://api.digitalocean.com/v2/actions/301502253"}]}}

如果我print_r()它并将其粘贴到JSONlint中它会验证,当我将print_r()的输出复制\粘贴到字符串中时它解码很好,但是当我直接从CURL响应解码它时它会返回而不是一个数组。

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,15);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     'Authorization: Bearer ----',
     'Content-Type: application/json',
     'Content-Length: ' . strlen($data_string))
);
$output = curl_exec($ch);
if(curl_errno($ch)){
    $error = 1;
}
curl_close($ch);
$data = json_decode($output);
print_r($data);

这是返回上述JSON而不是数组的代码。

1 个答案:

答案 0 :(得分:0)

添加此

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

这个mmakes curl将respnse返回到你的变量,没有它然后它只打印结果