PHP从API响应中获取json汇率值

时间:2015-05-28 17:40:42

标签: php json

我正在使用currencylayer JSON API来获取实时货币转换价值 - 是否有人知道如何使用PHP从API响应中获取"result"值和"quote"值?

我是PHP的新手,我想知道是否可以将它存储在变量中。

这是JSON:

{
  "success":true,
  "terms":"https:\/\/currencylayer.com\/terms",
  "privacy":"https:\/\/currencylayer.com\/privacy",
  "query":{
    "from":"CAD",
    "to":"GBP",
    "amount":234
  },
  "info":{
    "timestamp":1432829168,
    "quote":0.524191
  },
  "result":122.660694
}

我玩file_get_contents("URL"),但我不明白如何获得单一价值。

请求网址如下所示:

https://apilayer.net/api/convert?access_key=...&from=CAD&to=GBP&amount=234

感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

好的,我们假设json响应位于名为的变量中,您必须使用$response,然后执行以下操作:

json_decode

答案 1 :(得分:4)

试试这个

$jsonArray = file_get_contents($yourUrl);
$jsonObject = json_decode($jsonArray);
echo $jsonObject->result;
echo $jsonObject->info->quote;