我有一个CURL返回以下内容:
{"data":{"base":"BTC","currency":"USD","amount":"9342.29"}}
我正在尝试将金额JSON变量转换为PHP变量。我正在尝试以下尝试:
$result=curl_exec($ch);
//1
var_dump(json_decode($result));
//2
var_dump(json_decode($result, true));
//3
$data = json_decode($result[0]->data,true);
以前的var_dumps的响应是
//1
/home/usbanktech/public_html/bitcoin2.php:24:int 1
//2
/home/usbanktech/public_html/bitcoin2.php:26:int 1
//3
$data attempt returns nothing
试图将“ amount”:“ 9342.29”转换为类似$ amount的php。
完整代码:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.coinbase.com/v2/prices/BTC-USD/buy");
//curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"name\": \"New receive address\"}");
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c";
//$headers[] = "CB-ACCESS-KEY: <your api key>";
//$headers[] = "CB-ACCESS-SIGN: <the user generated message signature>";
//$headers[] = "CB-ACCESS-TIMESTAMP: <a timestamp for your request>";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result=curl_exec($ch);
// Closing
curl_close($ch);
$json = $result;
$array = json_decode($json,1);
$amount = $array['data']['amount'];
echo $amount;
答案 0 :(得分:0)
如何解码为数组并获取金额值?
<?php
$json = ' {"data":{"base":"BTC","currency":"USD","amount":"9342.29"}}';
$array = json_decode($json,1);
$amount = $array['data']['amount'];
echo $amount;
?>
或与extract()
<?php
$json = ' {"data":{"base":"BTC","currency":"USD","amount":"9342.29"}}';
$array = json_decode($json,1);
extract($array['data']);
echo $amount;
?>
答案 1 :(得分:0)
您需要将其设置为true才能获取json:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
否则,您将获得一个整数作为返回值。