插件80:汇率换算

<?php // Plug-in 80: Convert Currency
/*
 * 汇率换算
 * 插件说明:
 * 插件接受一个数值,把它从一种外汇换上成另一种外汇,
 * 若换算成功,则返回一个浮点数,准确到小数点的两位数,它表示个顶外汇转换新外汇后的金额。
 * 若换算失败,则返回false。
 * 它需要三个参数:
 * $amount 需要换算的金额
 * $from 源外汇的缩写
 * $to 目标外汇的缩写
 */
// This is an executable example with additional code supplied
// To obtain just the plug-ins please click on the Download link

$amount = 100;
$from   = 'USD';
$to     = 'GBP';

$result = PIPHP_ConvertCurrency(100, $from, $to);
if (!$result) echo "Conversion failed.";
else echo "$amount $from is $result $to";

function PIPHP_ConvertCurrency($amount, $from, $to)
{
   // Plug-in 80: Convert Currency
   //
   // This plug-in takes a value in one currency and converts
   // it to a value in a second currency. Upon success it
   // returns the converted value, otherwise it returns FALSE.
   // Tip: Once the $main[] array has been populated, you may
   // wish to cache the contents until the next day. This plug-in
   // requires the following arguments:
   //
   //    $amount: The amount of the first currency
   //    $from:   The first currency label
   //    $to:     The second currency label
   //
   //    The labels must be one of the following:
   //    AUD, BGN, BRL, CAD, CHF, CNY, CZK, DKK, EEK, EUR, GBP,
   //    HKD, HRK, HUF, IDR, INR, JPY, KRW, LTL, LVL, MXN, MYR,
   //    NOK, NZD, PHP, PLN, RON, RUB, SEK, SGD, THB, TRY, USD,
   //    ZAR

   $url   = 'http://www.ecb.europa.eu/stats/eurofxref/' .
            'eurofxref-daily.xml';
   $data  = file_get_contents($url);
   if (!strlen($data)) return FALSE;

   $ptr1  = strpos($data, '<Cube currency');
   $ptr2  = strpos($data, '</Cube>');
   $data  = substr($data, $ptr1, $ptr2 - $ptr1);
   $data  = str_replace("<Cube currency='", '', $data);
   $data  = str_replace("' rate='",        '|', $data);
   $data  = str_replace("'/>",             '@', $data);
   $data  = preg_replace("/\s/",            '', $data);
   $main  = array();
   $lines = explode('@', substr($data, 0, -1));

   foreach($lines as $line)
   {
      list($l, $r) = explode('|', $line);
      $main[$l]    = $r;
   }

   $main['EUR'] = 1;
   $from        = strtoupper($from);
   $to          = strtoupper($to);
   
   if (!isset($main[$from]) || !isset($main[$to])) return FALSE;
   return sprintf('%.02f', $amount / $main[$from] * $main[$to]);
}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值