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 相关文章推荐
WINDOWS 2000下使用ISAPI方式安装PHP
Sep 05 PHP
《PHP编程最快明白》第六讲:Mysql数据库操作
Nov 01 PHP
php调用Google translate_tts api实现代码
Aug 07 PHP
PHP关于IE下的iframe跨域导致session丢失问题解决方法
Oct 10 PHP
php日历制作代码分享
Jan 20 PHP
php判断手机访问还是电脑访问示例分享
Jan 20 PHP
PHP统计nginx访问日志中的搜索引擎抓取404链接页面路径
Jun 30 PHP
PHP封装的XML简单操作类完整实例
Nov 13 PHP
yii2 上传图片的示例代码
Nov 02 PHP
PHP下载大文件失败并限制下载速度的实例代码
May 10 PHP
php实现的支付宝网页支付功能示例【基于TP5框架】
Sep 16 PHP
php源码的安装方法和实例
Sep 26 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
Cakephp 执行主要流程
2010/03/24 PHP
基于curl数据采集之正则处理函数get_matches的使用
2013/04/28 PHP
win7+apache+php+mysql环境配置操作详解
2013/06/10 PHP
php模板引擎技术简单实现
2016/03/15 PHP
在Laravel5中正确设置文件权限的方法
2019/05/22 PHP
phpcmsv9.0任意文件上传漏洞解析
2020/10/20 PHP
javascript 清空form表单中某种元素的值
2009/12/26 Javascript
JavaScript 放大镜 放大倍率和视窗尺寸
2011/05/09 Javascript
js自动闭合html标签(自动补全html标记)
2012/10/04 Javascript
JS打开新窗口防止被浏览器阻止的方法
2015/01/03 Javascript
js提示框替代系统alert,自动关闭alert对话框的实现方法
2016/11/07 Javascript
搭建Bootstrap离线文档的方法
2016/12/02 Javascript
js实现本地图片文件拖拽效果
2017/07/18 Javascript
JavaScript定义及输出螺旋矩阵的方法详解
2017/12/01 Javascript
从parcel.js打包出错到选择nvm的全部过程
2018/01/23 Javascript
解决IE11 vue +webpack 项目中数据更新后页面没有刷新的问题
2018/09/25 Javascript
element-ui的回调函数Events的用法详解
2018/10/16 Javascript
[10:21]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Aster 选手采访
2021/03/11 DOTA
Python实现从脚本里运行scrapy的方法
2015/04/07 Python
利用python3随机生成中文字符的实现方法
2017/11/24 Python
安装python时MySQLdb报错的问题描述及解决方法
2018/03/20 Python
django多对多表的创建,级联删除及手动创建第三张表
2019/07/25 Python
详解Python中import机制
2020/09/11 Python
CSS3教程(1):什么是CSS3
2009/04/02 HTML / CSS
英国领先的奢侈品零售商之一:CRUISE
2016/12/02 全球购物
Tahari ASL官方网站:高级设计师女装
2021/03/15 全球购物
厨房工作人员岗位职责
2013/11/15 职场文书
2014信息技术专业毕业生自我评价
2014/01/17 职场文书
综治维稳工作承诺书
2014/08/30 职场文书
机械制造专业大学生自我鉴定
2014/09/19 职场文书
大学生村官个人总结
2015/02/15 职场文书
护士求职简历自我评价
2015/03/10 职场文书
在职证明范本
2015/06/15 职场文书
Mysql 性能监控及调优
2021/04/06 MySQL
CSS 伪元素::marker详解
2021/06/26 HTML / CSS
Python基础数据类型tuple元组的概念与用法
2021/08/02 Python