首页 > 解决方案 > 这个货币转换器 api 是如何工作的,获取汇率?

问题描述

我正在尝试使用这个 api(货币兑换 api)。这将返回如下内容:

{
  "from":"USD",
  "to":"HKD",
  "rate":7.7950999999999996958877090946771204471588134765625
}

我发送请求,file_get_contents()这似乎有效。我的问题是我无法访问数组 key rate

$r = file_get_contents('https://cc.hirak.cc/usd_hkd');
print_r($r['rate']); // nothing is shown. This is the problem.
print_r($r);  // result shows ( all the array ) 

我怎样才能只访问rate密钥?

标签: phpfixer.io

解决方案


你正在访问一个字符串而不是数组,试试这个代码,我认为这会起作用:

$r = json_encode(file_get_contents('https://cc.hirak.cc/usd_hkd'),true);

推荐阅读