【问题标题】:Currency conversion JSON API parsing with PHP用 PHP 解析货币转换 JSON API
【发布时间】:2012-03-13 09:42:09
【问题描述】:

谁能帮我用 PHP 解析这个 JSON API?我需要检索货币汇率。

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%3D%22eurusd%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=cbfunc

【问题讨论】:

标签: php json api parsing


【解决方案1】:

这是一个函数,您可以使用该函数使用相应的 3 个字符货币代码(即“USD”到“GBP”)将一种货币转换为另一种货币。

<?php

  function convertCurrencyUnit($from_Currency, $to_Currency, $unit_amount = 1) {

    $url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%3D%22' . $from_Currency . $to_Currency . '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';

    $rawdata = file_get_contents($url);
    $decodedArray = json_decode($rawdata, true);
    $converted_unit_amount = $decodedArray['query']['results']['rate']['Rate'];

    return $converted_unit_amount * $unit_amount;
  }

?>

例如看下面这个函数的简单调用。

<?php

  echo convertCurrencyUnit("USD", "GBP");  //Prints "0.5953" to the browser. The current conversion rate from US Dollar to British Pound as of 04-16-2014.

?>

另外,您可以在函数中传递一个可选的第三个参数,以便在转换完成后进行简单的乘法运算。

【讨论】:

    【解决方案2】:

    首先需要省略URL中的最后一个参数,去掉&amp;callback=cbfunc即可。

    获取内容的 PHP 代码是:

    $rawData = file_get_contents("... your url ...");
    $parsedData = json_decode($rawData);
    

    $parsedData 现在将包含嵌套对象结构中的内容。

    更多信息

    您需要启用 fopen 包装器才能使其工作。如果未启用,只需使用 cURL 从页面加载内容并将其放入json_decode

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2014-04-08
      • 1970-01-01
      相关资源
      最近更新 更多