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 相关文章推荐
关于php程序报date()警告的处理(date_default_timezone_set)
Oct 22 PHP
php上传文件中文文件名乱码的解决方法
Nov 01 PHP
ThinkPHP实现一键清除缓存方法
Jun 26 PHP
Php连接及读取和写入mysql数据库的常用代码
Aug 11 PHP
PHP获取当前相对于域名目录的方法
Jun 26 PHP
Zend Framework教程之Loader以及PluginLoader用法详解
Mar 09 PHP
PHP面向对象程序设计之对象生成方法详解
Dec 02 PHP
php实现支付宝当面付(扫码支付)功能
May 30 PHP
PHP 图片合成、仿微信群头像的方法示例
Oct 25 PHP
PHP实现笛卡尔积算法的实例讲解
Dec 22 PHP
基于PHP+mysql实现新闻发布系统的开发
Aug 06 PHP
如何在PHP中读写文件
Sep 07 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
德劲1102收音机的打理维修案例
2021/03/02 无线电
PHP中PDO基础教程 入门级
2011/09/04 PHP
PHP定时执行任务实现方法详解(Timer)
2015/07/30 PHP
[原创]php求圆周率的简单实现方法
2016/05/30 PHP
深入理解PHP原理之执行周期分析
2016/06/01 PHP
Yii2.0使用阿里云OSS的SDK上传图片、下载、删除图片示例
2017/09/20 PHP
解读IE和firefox下JScript和HREF的执行顺序
2008/01/12 Javascript
PHP 与 js的通信(via ajax,json)
2010/11/16 Javascript
一款基于jQuery的图片场景标注提示弹窗特效
2015/01/05 Javascript
jQuery验证插件validation使用指南
2015/04/21 Javascript
javascript实现表格增删改操作实例详解
2015/05/15 Javascript
jQuery实现默认是闭合的FAQ展开效果菜单
2015/09/14 Javascript
浅谈js的url解析函数封装
2016/06/28 Javascript
深入理解JavaScript中的for循环
2017/02/07 Javascript
vue.js开发环境安装教程
2017/03/17 Javascript
详解.vue文件中监听input输入事件(oninput)
2017/09/19 Javascript
Angularjs渲染的 using 指令的星级评分系统示例
2017/11/09 Javascript
微信小程序仿微信运动步数排行(交互)
2018/07/13 Javascript
解决vue this.$forceUpdate() 处理页面刷新问题(v-for循环值刷新等)
2018/07/26 Javascript
layer弹出层自适应高度,垂直水平居中的实现
2019/09/16 Javascript
Python中dictionary items()系列函数的用法实例
2014/08/21 Python
python实现指定字符串补全空格的方法
2015/04/30 Python
python创建关联数组(字典)的方法
2015/05/04 Python
python实现网站的模拟登录
2016/01/04 Python
python用装饰器自动注册Tornado路由详解
2017/02/14 Python
Python基于回溯法子集树模板解决数字组合问题实例
2017/09/02 Python
Python如何使用PIL Image制作GIF图片
2020/05/16 Python
python中字典增加和删除使用方法
2020/09/30 Python
Expedia意大利旅游网站:酒店、机票和租车预订
2017/10/30 全球购物
葛优非诚勿扰搞笑征婚台词
2014/03/17 职场文书
一岗双责责任书
2014/04/15 职场文书
给老婆的保证书怎么写
2015/05/08 职场文书
欢迎新生标语2015
2015/07/16 职场文书
《正面管教》读后有感:和善而坚定的旅程
2019/12/19 职场文书
jQuery实现影院选座订座效果
2021/04/13 jQuery
MySQL 数据表操作
2022/05/04 MySQL