使用PHP进行货币转换

时间:2010-07-19 15:41:41

标签: php api currency

我正在寻找一种方法,可以在网站上将任何金额从一种货币转换为另一种货币。用户输入类似“100”的内容并选择USD作为货币,然后选择澳元或加元作为转换的货币。当他点击“转换”按钮时,我想通过某些API自动转换该金额,并向他显示他选择转换为的货币金额。

有什么想法吗?

15 个答案:

答案 0 :(得分:8)

此方法使用Yahoo货币API 完整教程:Currency Converter in PHP, Python, Javascript and jQuery

function currencyConverter($currency_from, $currency_to, $currency_input) {
    $yql_base_url = "http://query.yahooapis.com/v1/public/yql";
    $yql_query = 'select * from yahoo.finance.xchange where pair in ("' . $currency_from . $currency_to . '")';
    $yql_query_url = $yql_base_url . "?q=" . urlencode($yql_query);
    $yql_query_url .= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    $yql_session = curl_init($yql_query_url);
    curl_setopt($yql_session, CURLOPT_RETURNTRANSFER, true);
    $yqlexec = curl_exec($yql_session);
    $yql_json =  json_decode($yqlexec, true);
    $currency_output = (float) $currency_input * $yql_json['query']['results']['rate']['Rate'];

    return $currency_output;
}

$currency_input = 2;
//currency codes : http://en.wikipedia.org/wiki/ISO_4217
$currency_from = "USD";
$currency_to = "INR";
$currency = currencyConverter($currency_from, $currency_to, $currency_input);

echo $currency_input . ' ' . $currency_from . ' = ' . $currency . ' ' . $currency_to;

答案 1 :(得分:6)

将EUR转换为USD

的示例
$url = 'http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=EUR&ToCurrency=USD';
            $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
            if($xml ===  FALSE)
            {
               //deal with error
            }
            else { 

                $rate = $xml;
            }

答案 2 :(得分:2)

我喜欢第一个解决方案,但似乎有关于它的大问题。 我试图将它实现到支付网关,但我一直得到1的结果。 这让我感到困惑,我最终发现这是因为谷歌为成千上万的水疗中心使用了一个空间。因此,当其余部分爆炸时,1 500.00的数量作为一个返回。我为它创建了一个快速而肮脏的修复程序。 如果有其他人遇到此问题,请告诉我。 这是我的解决方案:

function currency($from_Currency,$to_Currency,$amount) {
  $amount = urlencode($amount);
  $from_Currency = urlencode($from_Currency);
  $to_Currency = urlencode($to_Currency);
  $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
  $ch = curl_init();
  $timeout = 0;
  curl_setopt ($ch, CURLOPT_URL, $url);
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
  curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  $rawdata = curl_exec($ch);
  curl_close($ch);
  $data = explode('"', $rawdata);
  $data = explode('.', $data['3']);
  $data[0] = str_replace(" ", "",preg_replace('/\D/', '',  $data[0]));
  if(isset($data[1])){
    $data[1] = str_replace(" ", "",preg_replace('/\D/', '', $data[1]));
    $var = $data[0].".".$data[1];        
  } else{
    $var = $data[0];
  }
  return round($var,2); }

答案 3 :(得分:2)

这就是我正在使用的:

function exchangeRate( $amount, $from, $to)
{
    switch ($from) {
        case "euro":
            $from_Currency = "EUR";
            break;
        case "dollar":
            $from_Currency = "USD";
            break;
        case "pounds":
            $from_Currency = "GBP";
            break;
    }

    switch ($to) {
        case "euro":
            $to_Currency = "EUR";
            break;
        case "dollar":
            $to_Currency = "USD";
            break;
        case "pound":
            $to_Currency = "GBP";
            break;
    }

  $amount = urlencode($amount);

  $from_Currency = urlencode($from_Currency);
  $to_Currency = urlencode($to_Currency);
  $get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=" . $from_Currency . "&to=" . $to_Currency);

  $get = explode("<span class=bld>",$get);
  $get = explode("</span>",$get[1]);
  $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);
  return round($converted_amount, 2);
}

答案 4 :(得分:2)

我的2017解决方案是一个非常轻量级的函数,可以从fixer.io API获取当前的交换信息。它还将汇率存储在每日cookie中,以防止进一步繁重的Web加载时间。您也可以为此选择会话或删除它:

function convertCurrency($amount, $from = 'EUR', $to = 'USD'){
    if (empty($_COOKIE['exchange_rate'])) {
        $Cookie = new Cookie($_COOKIE);
        $curl = file_get_contents_curl('http://api.fixer.io/latest?symbols='.$from.','.$to.'');
        $rate = $curl['rates'][$to];
        $Cookie->exchange_rate = $rate;
    } else {
        $rate = $_COOKIE['exchange_rate'];
    }
    $output = round($amount * $rate);

    return $output;
}

将100欧元转换为磅的示例用法:

echo convertCurrency(100, 'EUR', 'GBP');

答案 5 :(得分:2)

将给定代码用于货币转换器PHP

public function convertCurrency($from, $to, $amount)    
{
    $url = file_get_contents('https://free.currencyconverterapi.com/api/v5/convert?q=' . $from . '_' . $to . '&compact=ultra');
    $json = json_decode($url, true);
    $rate = implode(" ",$json);
    $total = $rate * $amount;
    $rounded = round($total);
    return $total;
}

答案 6 :(得分:1)

/**
 * Rechnet den gegebenen Betrag von einer Währung in eine andere um
 * @param FLOAT $value
 * @param STRING $fromCurrency=USD Ursprungswärung des Betrags
 * @param STRING $toCurrency=EUR Zielwärhung, in die umgerechnet wird
 * @param BOOL $round=true Wenn aktiviert, wird der errechnete Wert auf 2 Nachkommastellen kaufmännisch gerundet
 * @return ARRAY [timestamp][datetime_iso][datetime_de][value][from][to][result]
 */
function calcCurrency($value=0, $fromCurrency='USD', $toCurrency='EUR', $round=true) {
    $timestamp = time();
    $fromCurrency = preg_replace('[^A-Z]', '', strtoupper(trim($fromCurrency)));
    $toCurrency = preg_replace('[^A-Z]', '', strtoupper(trim($toCurrency)));
    $round = (bool) $round;

    $wrongJSON = file_get_contents("http://www.google.com/ig/calculator?hl=en&q=1$fromCurrency=?$toCurrency");
    $search = array('lhs', 'rhs', 'error', 'icc');
    $replace = array('"lhs"', '"rhs"', '"error"', '"icc"');
    $json = str_replace($search, $replace, $wrongJSON);
    $jsonData = json_decode($json, true);
    if ('' !== $jsonData['error']) throw new Exception('FEHLER: '.$jsonData['error']);
    $rhs = explode(' ', $jsonData['rhs'], 2);

    $calcValue = floatval(0.00);
    $value = floatval($value);
    $ratio = floatval($rhs[0]);

    // Gültigkeitsprüfungen
    if ($value < 0) throw new Exception('Umzurechnender Wert darf nicht negativ sein.');

    // Plausibilitätsprüfung der eingestellten Währung und Festlegung
    if ($toCurrency == $fromCurrency) {
        // Ursprungswährung = Zielwährung | Es erfolgt keine Berechnung
        $calcValue = $value;
        $ratio = 1;
    } else {
        $calcValue = floatval($value * $ratio);
    }

    // Array mit Rückgabewerten erzeugen und zurück geben
    return array(
        'timestamp' => $timestamp,
        'datetime_iso' => date('Y-m-d H:i:s', $timestamp),
        'datetime_de' => date('d.m.Y H:i:s', $timestamp),
        'value' => $value,
        'from' => $fromCurrency,
        'to' => $toCurrency,
        'ratio' => round($ratio, 6),
        'result' => (true===$round)
            ? round($calcValue, 2)
            : $calcValue
    );
}

答案 7 :(得分:1)

我使用以下PHP从ECB中提取数据Stefan Gehrig建议。

<?php
try {
    $xml_string = file_get_contents("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
    $xml = new SimpleXMLElement($xml_string);
    $cxml = $xml->xpath('//*[@currency]');
    //anchored to USD in this case
    $usx = $xml->xpath('//*[@currency="USD"]');
    $base = floatval(strval($usx[0]['rate']));
    //create a simple associative array with the 3-letter code
    //as the key and the rate as the value
    $c_arr = array();
    foreach ($cxml as $c) {
        $cur = strval($c['currency']);
        $rate = floatval(strval($c['rate']))/$base;
        $c_arr[$cur] = $rate;
    }
    //add the euro since it's assumed as the base rate for the ECB
    $c_arr['EUR'] = 1/$base;
    $currency_json = json_encode($c_arr);

    //write to file
    $file = "currency.json";
    $fh = fopen($file, 'w') or die("can't open file");
    fwrite($fh, $currency_json);
    fclose($fh);
    echo $currency_json;
} catch (Exception $e) { echo $e; }
?>

它写了一个我作为JavaScript变量包含的JSON文件:

<script type="text/javascript">
var data = <?php include('currency.json'); ?>;
</script>

当请求货币更改时,我可以使用带有JavaScript的3个字母的货币代码(例如,data['GBP'])轻松获取数据。

我使用Cron作业每天更新一次JSON,因此每次访问页面时都不会打电话。

答案 8 :(得分:1)

使用这个简单的功能:

function convertCurrency($amount, $from, $to){
    $url  = "https://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
    $data = file_get_contents($url);
    preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
    $converted = preg_replace("/[^0-9.]/", "", $converted[1]);
    return round($converted, 3);
}

答案 9 :(得分:0)

如果你使用像wamp或xampp这样的本地服务器或其他服务器,这很简单,那么你必须首先在php.ini中启用openssl的扩展

extension=php_openssl.dll `allow_url_fopen = On`

然后您就可以运行我的代码了  否则你运行你的网站与在线托管然后你不需要这样做所以你必须在你的PHP脚本中添加这个PHP功能

<?php
function currencyCnv( $amount, $from, $to){
$get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=" . $from. "&to=" . $to);
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$converted_amount = $get[0];
echo round($converted_amount,2);
}

  currencyCnv(100,'GBP','PKR');
//currencyCnv(you amount from form input filed ,currency from select box,currency to select box)
//any currency convert with this code 

答案 10 :(得分:0)

您还可以查看:https://free.currencyconverterapi.com

免责声明,我是本网站的作者。

示例转换网址为:http://free.currencyconverterapi.com/api/v6/convert?q=PHP_EUR,EUR_PHP&compact=ultra&apiKey=sample-api-key,它将返回json格式的值,例如: { “PHP_EUR”:0.016434, “EUR_PHP”:60.849184}

您应该注意这些限制,但最重要的请求和查询(详情见网站)。我已经实施了限制,因为有滥用服务的人。

我从2014年开始这样做,并且从那时起就开始了(除了链接更改和维护停机时间)。我个人将它用于我的其他网站,并公开提供服务,以便它也可以帮助其他开发者。

无论如何希望这会有所帮助,这里有一个示例PHP代码:

<?php
function convertCurrency($amount, $from, $to){
  $conv_id = "{$from}_{$to}";
  $string = file_get_contents("https://free.currencyconverterapi.com/api/v6/convert?q=$conv_id&compact=ultra&apiKey=sample-api-key");
  $json_a = json_decode($string, true);

  return $amount * round($json_a[$conv_id], 4);
}

echo(convertCurrency(5, "USD", "PHP"));
?> 

答案 11 :(得分:0)

请查看以下货币兑换示例。

    function oneUSDTo($amount, $toCurrency)
{
$currencyUrl = $amount."usd+to+$toCurrency";
$url = "https://www.google.com/search?q=".$currencyUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);
$data = explode("$amount US Dollar = ",$result);
return (float) substr($data[1],0,10);
}

//Usage: oneUSDTo("type currency code here");
echo oneUSDTo("5","EUR");

答案 12 :(得分:0)

https://fincharts.info/charts/exchange/?key=api_key&&from=USD&to=GBP,BWP,ZAR&amount=45854&date=2018-03-03&base=USD

我认为您似乎必须注册一个api密钥

答案 13 :(得分:0)

首先,从此网站获得免费的API:

fixer.io

第二,在此处替换它:

<?php
$API = '3259bbede76b961c84a5244a0';
function convertCurrency($API, $amount, $from = 'EUR', $to = 'USD'){
$curl = file_get_contents("http://data.fixer.io/api/latest?access_key=$API&symbols=$from,$to");
$arr = json_decode($curl,true);

$from = $arr['rates'][$from];
$to = $arr['rates'][$to];

$rate = $to / $from;
$result = round($amount * $rate, 6);
return $result;
}

然后,以这种方式使用它并享受它!

echo convertCurrency($API, 1, 'USD', 'EGP');

答案 14 :(得分:-1)

大量搜索后,发现了这个。

// Fetching JSON
$req_url = 'https://api.exchangerate-api.com/v4/latest/USD';
$response_json = file_get_contents($req_url);

// Continuing if we got a result
if(false !== $response_json) {

    // Try/catch for json_decode operation
    try {

    // Decoding
    $response_object = json_decode($response_json);

    // YOUR APPLICATION CODE HERE, e.g.
    $base_price = 12; // Your price in USD
    $EUR_price = round(($base_price * $response_object->rates->EUR), 2);

    }
    catch(Exception $e) {
        // Handle JSON parse error...
    }
}

这很好。 该摘录来自:https://www.exchangerate-api.com/docs/php-currency-api