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 相关文章推荐
PHP4实际应用经验篇(3)
Oct 09 PHP
MySQL中create table语句的基本语法是
Jan 15 PHP
php 小乘法表实现代码
Jul 16 PHP
收集的二十一个实用便利的PHP函数代码
Apr 22 PHP
php 上一篇,下一篇文章实现代码与原理说明
May 09 PHP
PHP面向对象程序设计之类常量用法实例
Aug 20 PHP
php中json_encode UTF-8中文乱码的更好解决方法
Sep 28 PHP
php实现压缩多个CSS与JS文件的方法
Nov 11 PHP
使用Thinkphp框架开发移动端接口
Aug 05 PHP
Laravel Intervention/image图片处理扩展包的安装、使用与可能遇到的坑详解
Nov 14 PHP
thinkphp3.2.0 setInc方法 源码全面解析
Jan 29 PHP
PHP+RabbitMQ实现消息队列的完整代码
Mar 20 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
自己做矿石收音机
2021/03/02 无线电
php全局变量和类配合使用深刻理解
2013/06/05 PHP
整理php防注入和XSS攻击通用过滤
2015/09/13 PHP
详解WordPress中添加友情链接的方法
2016/05/21 PHP
Yii2框架实现数据库常用操作总结
2017/02/08 PHP
使用PHPStorm+XDebug搭建单步调试环境
2017/11/19 PHP
js function使用心得
2010/05/10 Javascript
javascript下高性能字符串连接StringBuffer类
2010/08/16 Javascript
js的.innerHTML = &quot;&quot;IE9下显示有错误的解决方法
2013/09/16 Javascript
父节点获取子节点的字符串示例代码
2014/02/26 Javascript
JS截取url中问号后面参数的值信息
2014/04/29 Javascript
jquery+css3实现网页背景花瓣随机飘落特效
2015/08/17 Javascript
Javascript控制div属性动态变化实例分析
2015/10/08 Javascript
JavaScript面试开发常用的知识点总结
2016/08/08 Javascript
javascript实现圣旨卷轴展开效果(代码分享)
2017/03/23 Javascript
老生常谈js数据类型
2017/08/03 Javascript
Vue按需加载的具体实现
2017/12/02 Javascript
layui radio性别单选框赋值方法
2018/08/15 Javascript
vue中使用带隐藏文本信息的图片、图片水印的方法
2020/04/24 Javascript
如何在vue 中使用柱状图 并自修改配置
2021/01/21 Vue.js
[01:46]新英雄登场
2019/09/10 DOTA
浅谈Python中的作用域规则和闭包
2018/03/20 Python
django+mysql的使用示例
2018/11/23 Python
Python生成词云的实现代码
2020/01/14 Python
Python的PIL库中getpixel方法的使用
2020/04/09 Python
python调用API接口实现登陆短信验证
2020/05/10 Python
世界上最好的帽子:Tilley
2016/11/27 全球购物
行政主管岗位职责
2013/11/18 职场文书
公司授权委托书范本
2014/04/03 职场文书
《春天来了》教学反思
2014/04/07 职场文书
企业法律事务工作总结
2015/08/11 职场文书
2016感恩母亲节校园广播稿
2015/12/17 职场文书
2016年五一促销广告语
2016/01/28 职场文书
复制别人的成功真的会成功吗?
2019/10/17 职场文书
MySQL连接控制插件介绍
2021/09/25 MySQL
世界十大评分最高的动漫,CLANNAD上榜,第八赚足人们眼泪
2022/03/18 日漫