我正在尝试访问以下JSON文件的“rates”对象中的某种货币(例如GBP)的值:
JSON文件:
{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}
这是我的方法:
PHP(CURL):
$url = ...
// initialize CURL:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// get the (still encoded) JSON data:
$json = curl_exec($ch);
curl_close($ch);
// store decoded JSON Response in array
$exchangeRates = (array) json_decode($json);
// access parsed json
echo $exchangeRates['rates']['GBP'];
但它不起作用。
现在,当我尝试访问JSON文件的“timestamp”值时,如下所示:
echo $exchangeRates['timestamp'];
它工作正常。
有什么想法吗?
答案 0 :(得分:1)
这是解决方案。
$exchangeRates = (array) json_decode($json,TRUE);
你要做的就是使用json_decode函数的第二个参数。
这是完整的代码段。
<?php
$json='{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}';
$exchangeRates = (array) json_decode($json,TRUE);
echo $exchangeRates["rates"]["GBP"];
?>