Currency

联合创作 · 2023-10-02 15:36

Currency: an unobstrusive automatic and real time currency conversion

This is a small tool that may prove to be usefull. It permits automatically converting any currency to any other currency on a website, with real time quotes. It is

implemented using an ajax PHP script backend (for cross-domain issue).

How to install:

Simply copy the currency-ajax.php file to the website (for example in the root folder), the jquery.currency.js and currency.css files. In addition, you can use the set

of icons provided in the package, or your own.

How it works:

Currency reads automatically traverses the DOM and processes every element tag with class currency. Each automatically converted currency value uses the

rel= tag for the options.

Here is an example:

<span class="currency" rel="USD:EUR:&euro;">24.95</span>

The first parameter is the currency "from". The second parameter is the currency "to" and the optional third parameter is the currency symbol to be prepended to the

converted numeric value.

In addition to converting the value, the script also add the "currency to" code to the element class. Using CSS you can style the .currency element to have a country

flag for example based on the currency code.

Ajax

Currency uses ajax and in order to bypass cross-domain restrictions, it uses a simple .php script. The script sends a request to yahoo finance to retrieve the latest

rates for the "from" and "to" currencies.

jQuery cookie

Currency uses the jquery.cookie plugin to store the retrieve rates. Our implementation uses a modified version of the cookie plugin to accept delays in hours instead of

days (see the delay set to 6 in the currency script). The purpose of this is to prevent querying the ajax backend everytime a user reloads the page.

Code

jquery.currency.js

/**
* Currency (http://www.reality-xp.com)
* A jQuery plugin for converting currencies
*
* Version 1.0
* August 27th, 2008
*
* Copyright (c) 2008 Reality XP
* Dual licensed under the MIT and GPL licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.opensource.org/licenses/gpl-license.php
*
**/

//on page load call convert
$(document).ready(function(){$('.currency').each(function(i,domEle){$(domEle).convertCurrency(false);return true;})});

;(function(){

var $$;

$$ = jQuery.fn.convertCurrency = function(currencycode) {
var $this = $(this)
if ($this.attr('rel'))
{
var prms = $this.attr('rel').split(':'); /*"USD:EUR:€"*/
var fAmnt = parseFloat($this.text());
var cCode = currencycode ? ' '+prms[1] : '';
// check if the exchange rate has been retrieved today
var cookieVal = $.cookie('currencyrate'+prms[0]+prms[1]);
if (cookieVal != null)
{
frmtCurrency($this,prms[2],fAmnt*parseFloat(cookieVal),cCode,prms[1]);
}
else
{
try {
reqAjax = $.ajax({
type: "POST",
url: '/currency-ajax.php',
dataType: "json",
data: "action=rate" + "&currfrom=" + prms[0] + "&currto=" + prms[1],
success: function(json) {
switch (json.errcode) {
case 'ERR-100':
$.cookie('currencyrate'+prms[0]+prms[1],json.result,{expires: 6, path: '/' });
frmtCurrency($this,prms[2],fAmnt*parseFloat(json.result),cCode,prms[1]);
break;
case 'ERR-200':
break;
default:
break
}
},
error: function(xhr, msg, ex) {
reqAjax = null
}
})
} catch(e) {
}
}
}
return this;

function frmtCurrency(ele,symb,val,code,cls) {
// round the currency to the nearest .05
val *= 2.0;
val = val.toFixed(1) / 2.0;
val = val.toFixed(2);
// build the text in the form: '$' '12.35' 'USD'
ele.text(symb+val+code );
// add the currency code to the element class.
ele.addClass(cls);
};

};

})();

currency-ajax.php

<?php
/*
Filename:         rxpcur-ajax.php
Date:             2008-08-27
Copyright:         2008, Reality XP
Author:         Reality XP
Description:     PHP Back-end to fetch Currency Conversion Rates from Yahoo! Finance.
License:        GPL
Inspired by:    http://www.talkphp.com/general/1422-creating-simple-currency-converter-a...
                http://chaos-laboratory.com/2007/03/01/currex-ajax-based-currency-conver...
*/

// Exit if no function specified
if( !isset( $_POST['action'] ) || '' == $_POST['action'] ) {
    echo
'{ errcode: "ERR-000", errmsg: "No action specified" }';
    exit();
}

switch (
$_POST['action']) {
   
    case
'rate':
       
$currfrom = $_POST['currfrom'];
       
$currto = $_POST['currto'];
       
$conversion_rate = get_conversion_rate( $currfrom, $currto );
           
        if(
$conversion_rate != false ) {
           
$result = $conversion_rate * 1.0;
            echo
'{ errcode: "ERR-100", errmsg: "Conversion Successful", result: "' . $result . '" }';
            exit();
        }
        else {
            echo
'{ errcode: "ERR-200", errmsg: "Error contacting Yahoo! Finance" }';
            exit();
        }
        break;
       
    default:
        echo
'{ errcode: "ERR-210", errmsg: "Unknown conversion error" }';
        exit();
}

function
get_conversion_rate( $cur_from, $cur_to ) {

    if(
strlen( $cur_from ) == 0 )
       
$cur_from = "USD";

    if(
strlen( $cur_to ) == 0 )
       
$cur_to = "USD";

    if (
$cur_from == $cur_to)
        return
"1.0";
               
   
$data = "";
   
$host = "download.finance.yahoo.com";
   
$fp = @fsockopen( $host, 80, $errno, $errstr, 30 );
    if ( !
$fp ) {
       
$errorstr = "$errstr ($errno)<br />\n";
        return
false;
    }
    else {
       
// Build Query String
        // Query URL: http://download.finance.yahoo.com/d/quotes.csv?s=[$cur_from][$cur_to]=X&f=l1
        // Returns: A Plain Text file which contains the current exchange rate
        // Example content: 32.15
        //                    The source and destination currencies used here
        //                    were USD (US Dollar) and GBP (Great Britain Pound)
       
$file = "/d/quotes.csv";
       
$str = "?s=" . $cur_from . $cur_to . "=X&f=l1";
       
$out = "GET " . $file . $str . " HTTP/1.0\r\n";
       
$out .= "Host: www.yahoo.com\r\n";
       
$out .= "Connection: Close\r\n\r\n";
       
        @
fputs( $fp, $out );
        while( !@
feof( $fp ) )
           
$data .= @fgets( $fp, 128 );
        @
fclose( $fp );

        @
preg_match( "/^(.*?)\r?\n\r?\n(.*)/s", $data, $match );
       
$data = $match[2];
        return
$data;
    }
//else
}//end get_conversion
   
?>

sample use

with automatic conversion from USD to EUR

<span class="currency" rel="USD:EUR:&euro;">24.95</span>

with automatic conversion from USD to GBP

<span class="currency" rel="USD:GBP:&pound;">24.95</span>

with no conversion to display USD with flag from the CSS (same styling as with other converted currencies

<span class="currency USD">$24.95</span>

Example html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name='copyright' content='Copyright (c) 2001-2008 by Reality XP' />
<title>JQuery Currency</title>
<script src="/scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="/scripts/jquery.cookie.js"></script>
<script type="text/javascript" src="/scripts/jquery.currency.js"></script>
<link href="/currency.css" rel="stylesheet" type="text/css" media="all" />
</head>
<body>
<span class="currency" rel="USD:EUR:&euro;">24.95</span>
<span class="currency" rel="USD:GBP:&pound;">24.95</span>
<span class="currency USD">$24.95</span>
</body>
</html>
浏览 3
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报