我正在尝试使用此api链接获得当前的美元/欧元汇率:
http://api.fixer.io/latest?base=USD&symbols=EUR
使用此代码:
$url = "http://api.fixer.io/latest?base=USD&symbols=EUR";
$json = json_decode(file_get_contents($url), true);
$price = $json->rates[0]->EUR;
我想要$price
的结果像:"0.84782"
,但似乎我做错了什么?
<?php
$url = "http://api.fixer.io/latest?base=USD&symbols=EUR";
$json = json_decode(file_get_contents($url), true);
$price=$json['rates']['EUR'];
echo $price;
这对你有用。您要查找的价格是嵌套数组,因此您必须首先访问父级数据。
您正在将true
传递给json_decode,因此返回的值是一个数组。要使用对象,请删除true
,如下所示:
$json = json_decode(file_get_contents($url));
像这样访问它:
echo $json->rates->EUR; // Output is: 0.84782
如果要访问数组样式:
$json = json_decode(file_get_contents($url), true);
echo $json['rates']['EUR']; // 0.84782