PHP实现货币换算的方法


Posted in PHP onNovember 29, 2014

本文实例讲述了PHP实现货币换算的方法。分享给大家供大家参考。

具体实现代码如下:

<?php 

/* 

* File: CurrencyConverter.php 

* Author: Simon Jarvis 

* Copyright: 2005 Simon Jarvis 

* Date: 10/12/05 

* Link: http://www.white-hat-web-design.co.uk/articles/php-currency-conversion.php 

* 

* This program is free software; you can redistribute it and/or 

* modify it under the terms of the GNU General Public License 

* as published by the Free Software Foundation; either version 2 

* of the License, or (at your option) any later version. 

* 

* This program is distributed in the hope that it will be useful, 

* but WITHOUT ANY WARRANTY; without even the implied warranty of 

* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

* GNU General Public License for more details: 

* http://www.gnu.org/licenses/gpl.html 

* 

*/ 

class CurrencyConverter { 

   var $xml_file = "www.ecb.int/stats/eurofxref/eurofxref-daily.xml"; 

   var $mysql_host, $mysql_user, $mysql_pass, $mysql_db, $mysql_table; 

   var $exchange_rates = array(); 

   //Load Currency Rates 

   function CurrencyConverter($host,$user,$pass,$db,$tb) { 

      $this->mysql_host = $host; 

      $this->mysql_user = $user; 

      $this->mysql_pass = $pass; 

      $this->mysql_db = $db; 

      $this->mysql_table = $tb; 

      $this->checkLastUpdated(); 

      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); 

      $rs = mysql_select_db($this->mysql_db,$conn); 

      $sql = "SELECT * FROM ".$this->mysql_table; 

      $rs =  mysql_query($sql,$conn); 

      while($row = mysql_fetch_array($rs)) { 

         $this->exchange_rates[$row['currency']] = $row['rate']; 

      } 

   } 

   /* Perform the actual conversion, defaults to £1.00 GBP to USD */ 

   function convert($amount=1,$from="GBP",$to="USD",$decimals=2) { 

      return(number_format(($amount/$this->exchange_rates[$from])*$this->exchange_rates[$to],$decimals)); 

   } 

   /* Check to see how long since the data was last updated */ 

   function checkLastUpdated() { 

      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); 

      $rs = mysql_select_db($this->mysql_db,$conn); 

      $sql = "SHOW TABLE STATUS FROM ".$this->mysql_db." LIKE '".$this->mysql_table."'"; 

      $rs =  mysql_query($sql,$conn); 

      if(mysql_num_rows($rs) == 0 ) { 

         $this->createTable(); 

      } else { 

         $row = mysql_fetch_array($rs); 

         if(time() > (strtotime($row["Update_time"])+(12*60*60)) ) { 

            $this->downloadExchangeRates(); 

         } 

      } 

   } 

   /* Download xml file, extract exchange rates and store values in database */ 

   function downloadExchangeRates() { 

      $currency_domain = substr($this->xml_file,0,strpos($this->xml_file,"/")); 

      $currency_file = substr($this->xml_file,strpos($this->xml_file,"/")); 

      $fp = @fsockopen($currency_domain, 80, $errno, $errstr, 10); 

      if($fp) { 

         $out = "GET ".$currency_file." HTTP/1.1rn"; 

         $out .= "Host: ".$currency_domain."rn"; 

         $out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5rn"; 

         $out .= "Connection: Closernrn"; 

         fwrite($fp, $out); 

         while (!feof($fp)) { 

            $buffer .= fgets($fp, 128); 

         } 

         fclose($fp); 

         $pattern = "{<Cubes*currency='(w*)'s*rate='([d.]*)'/>}is"; 

         preg_match_all($pattern,$buffer,$xml_rates); 

         array_shift($xml_rates); 

         for($i=0;$i<count($xml_rates[0]);$i++) { 

            $exchange_rate[$xml_rates[0][$i]] = $xml_rates[1][$i]; 

         } 

         $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); 

         $rs = mysql_select_db($this->mysql_db,$conn); 

         foreach($exchange_rate as $currency=>$rate) { 

            if((is_numeric($rate)) && ($rate != 0)) { 

               $sql = "SELECT * FROM ".$this->mysql_table." WHERE currency='".$currency."'"; 

               $rs =  mysql_query($sql,$conn) or die(mysql_error()); 

               if(mysql_num_rows($rs) > 0) { 

                  $sql = "UPDATE ".$this->mysql_table." SET rate=".$rate." WHERE currency='".$currency."'"; 

               } else { 

                  $sql = "INSERT INTO ".$this->mysql_table." VALUES('".$currency."',".$rate.")"; 

               } 

               $rs =  mysql_query($sql,$conn) or die(mysql_error()); 

            } 

         } 

      } 

   } 

   /* Create the currency exchange table */ 

   function createTable() { 

      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); 

      $rs = mysql_select_db($this->mysql_db,$conn); 

      $sql = "CREATE TABLE ".$this->mysql_table." ( currency char(3) NOT NULL default '', rate float NOT NULL default '0', PRIMARY KEY(currency) ) ENGINE=MyISAM"; 

      $rs =  mysql_query($sql,$conn) or die(mysql_error()); 

      $sql = "INSERT INTO ".$this->mysql_table." VALUES('EUR',1)"; 

      $rs =  mysql_query($sql,$conn) or die(mysql_error()); 

      $this->downloadExchangeRates(); 

   } 

} 

?>

上面的代码复制到一个新文件并将其保存为CurrencyConverter.php。当你需要转换包含类文件,称为“转换”功能。你需要输入自己的mysql数据库变量如登录详细信息。下面的例子将£2.50英镑转换成美元(美元)。
<?php 

   include('CurrencyConverter.php'); 

   $x = new CurrencyConverter('your_host','your_username','your_password','your_database_name','your_table_name'); 

   echo $x->convert(2.50,'GBP','USD'); 

?>

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
打造计数器DIY三步曲(下)
Oct 09 PHP
PHP中Session的概念
Oct 09 PHP
PHP 危险函数全解析
Sep 09 PHP
PHP utf-8编码问题,utf8编码,数据库乱码,页面显示输出乱码
Apr 08 PHP
基于Zend的Config机制的应用分析
May 02 PHP
完美实现wordpress禁止文章修订和自动保存的方法
Nov 03 PHP
php curl模拟post请求和提交多维数组的示例代码
Nov 19 PHP
PHP正则匹配操作简单示例【preg_match_all应用】
Jul 10 PHP
PHP设计模式之工厂方法设计模式实例分析
Apr 25 PHP
PHP实现转盘抽奖算法分享
Apr 15 PHP
PHP面向对象程序设计之对象克隆clone和魔术方法__clone()用法分析
Jun 12 PHP
禁止直接访问php文件代码分享
May 05 PHP
php实现的树形结构数据存取类实例
Nov 29 #PHP
Codeigniter购物车类不能添加中文的解决方法
Nov 29 #PHP
ThinkPHP模版中导入CSS和JS文件的方法
Nov 29 #PHP
ThinkPHP中Session用法详解
Nov 29 #PHP
thinkphp的静态缓存用法分析
Nov 29 #PHP
thinkphp中memcache的用法实例
Nov 29 #PHP
thinkPHP实现瀑布流的方法
Nov 29 #PHP
You might like
在windows平台上构建自己的PHP实现方法(仅适用于php5.2)
2013/07/05 PHP
php include类文件超时问题处理
2015/02/06 PHP
Laravel 5.5 实现禁用用户注册示例
2019/10/24 PHP
php中加密解密DES类的简单使用方法示例
2020/03/26 PHP
HTML中不支持静态Expando的元素的问题
2007/03/08 Javascript
深入聊聊Array的sort方法的使用技巧.详细点评protype.js中的sortBy方法
2007/04/12 Javascript
javascript:文字不间断向左移动的实例代码
2013/08/08 Javascript
浅谈Javascript中的12种DOM节点类型
2016/08/19 Javascript
jQuery实现图片轮播效果代码
2016/09/27 Javascript
jQuery的时间datetime控件在AngularJs中的使用实例(分享)
2017/08/17 jQuery
jQuery实现获取当前鼠标位置并输出功能示例
2019/01/05 jQuery
微信小程序分享功能onShareAppMessage(options)用法分析
2019/04/24 Javascript
浅谈使用nodejs搭建web服务器的过程
2020/07/20 NodeJs
[12:51]71泪洒现场!是DOTA2让经典重现
2014/03/24 DOTA
[03:56]DOTA2完美大师赛趣味视频之小鸽子和Mineski打台球
2017/11/24 DOTA
python解析xml文件实例分享
2013/12/04 Python
Python中List.count()方法的使用教程
2015/05/20 Python
Python数据类型详解(四)字典:dict
2016/05/12 Python
Python 元类实例解析
2018/04/04 Python
Python爬取视频(其实是一篇福利)过程解析
2019/08/01 Python
详解Python3 pandas.merge用法
2019/09/05 Python
django 实现celery动态设置周期任务执行时间
2019/11/19 Python
解决django中form表单设置action后无法回到原页面的问题
2020/03/13 Python
TensorFlow keras卷积神经网络 添加L2正则化方式
2020/05/22 Python
pycharm 的Structure界面设置操作
2021/02/05 Python
用css3实现转换过渡和动画效果
2020/03/13 HTML / CSS
英国外籍人士的在线超市:British Corner Shop
2019/06/03 全球购物
英国领先的游戏零售商:GAME
2019/09/24 全球购物
户外亲子活动策划方案
2014/02/07 职场文书
《翻越远方的大山》教学反思
2014/04/13 职场文书
《吃水不忘挖井人》教学反思
2014/04/15 职场文书
黄石寨导游词
2015/02/05 职场文书
培养联系人考察意见
2015/06/01 职场文书
读《茶花女》有感:山茶花的盛开与凋零
2020/01/17 职场文书
python的netCDF4批量处理NC格式文件的操作方法
2022/03/21 Python
详解Alibaba Java诊断工具Arthas查看Dubbo动态代理类
2022/04/08 Java/Android