使用PHP进行货币转换JSON API解析

Could anyone help me parse this JSON API with PHP? I need to retrieve the currency exchange rate.

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

At first you need to omit the last parameter in the URL, just remove &callback=cbfunc.

The PHP code to fetch the content is:

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

$parsedData will now contain the content in a nested object structure.

Further info

You need fopen wrappers enabled for this to work. If they are not enabled, just use cURL to load the content from the page and put it into json_decode.

Here is a function that you can use to convert a currency to another currency using the respective 3 character currency codes (i.e. "USD" to "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;
  }

?>

For example, see the following simple call of this function.

<?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.

?>

Also, you can pass an optional third parameter into the function to do a simple multiplication after the conversion is done.